// ==PREPROCESSOR==
// @name "Biography, albums, title, similar artist info.www.last.fm."
// @version "13072019"
// @author "kgena_ua"
// @feature "v1.4"
// @feature "watch-metadb"
// ==/PREPROCESSOR==

function RGB(r,g,b){
    return (0xff000000|(r<<16)|(g<<8)|(b));
}

function RGBA(r,g,b,a){
    return ((a << 24) | (r << 16) | (g << 8) | (b));
}

function getRed(color){
    return ((color >> 16) & 0xff);
}

function getGreen(color){
    return ((color >> 8) & 0xff);
}

function getBlue(color){
    return (color & 0xff);
}

function combineColors(c1, c2){
    var c1 = toRGB(c1);
    var c2 = toRGB(c2);

    var r = Math.round((c1[0] + c2[0]) / 2);
    var g = Math.round((c1[1] + c2[1]) / 2);
    var b = Math.round((c1[2] + c2[2]) / 2);

    return (0xff000000 | (r << 16) | (g << 8) | (b));
}

function toRGB(d){
    var d = d-0xff000000;
    var r = d >> 16;
    var g = d >> 8 & 0xFF;
    var b = d & 0xFF;

    return [r,g,b];
}

DT_LEFT = 0x00000000;
DT_RIGHT = 0x00000002;
DT_CENTER = 0x00000001;
DT_VCENTER = 0x00000004;
DT_SINGLELINE = 0x00000020;
DT_WORD_ELLIPSIS = 0x00040000;
DT_WORDBREAK = 0x00000010;
DT_CALCRECT = 0x00000400;
DT_NOPREFIX = 0x00000800;

MF_ENABLED = 0x00000000;
MF_GRAYED = 0x00000001;
MF_SEPARATOR = 0x00000800;

IDC_HAND = 32649;
IDC_ARROW = 32512;

ENTER = 13;
BACKSPACE = 8;
ESC = 27;

VK_SHIFT = 0x10;
VK_CONTROL = 0x11;
VK_PAGE_UP = 0x21;
VK_PAGE_DOWN = 0x22;
VK_END = 0x23;
VK_HOME = 0x24;
VK_LEFT = 0x25;
VK_UP = 0x26;
VK_RIGHT = 0x27;
VK_DOWN = 0x28;

var ww = 800, wh = 800;

String.prototype.repeat = function(n) {
    return new Array(n + 1).join(this);
}

window.SetProperty(" - user", "");
if (window.GetProperty(" - user") != "" ) window.SetProperty(" - user", "");
window.SetProperty("- user", "");
if (window.GetProperty("- user") != "" ) window.SetProperty("- user", "");
window.SetProperty("_".repeat(50), "");
if (window.GetProperty("_".repeat(50)) != "" ) window.SetProperty("_".repeat(50), "");

var text_alignment = [
    ["Left", DT_VCENTER | DT_LEFT | DT_NOPREFIX],
    ["Center", DT_VCENTER | DT_CENTER | DT_NOPREFIX],
    ["Right" , DT_VCENTER | DT_RIGHT | DT_NOPREFIX]
];

var font_style = [
    ["Normal", 0],
    ["Bold", 1],
    ["Italic" , 2],
    ["Bold italic" , 3]
];

var text_alignment_h0 = window.GetProperty(" text alignment : header 0 (0, 1, 2)", 0);
var text_alignment_h1 = window.GetProperty("text alignment : header 1", 2);
var text_alignment_h2 = window.GetProperty("text alignment : header 2", 2);
var text_alignment_t = window.GetProperty("text alignment : text", 0);

var font_name_h0 = window.GetProperty(" text: font name: header 0", "Times New Roman");
var font_name_h1 = window.GetProperty(" text: font name: header 1", "Times New Roman");
var font_name_h2 = window.GetProperty(" text: font name: header 2", "Times New Roman");
var font_name_t = window.GetProperty(" text: font name: text", "Times New Roman");

var font_size_h0 = window.GetProperty("text: font size: header 0", 16);
var font_size_h1 = window.GetProperty("text: font size: header 1", 24);
var font_size_h2 = window.GetProperty("text: font size: header 2", 16);
var font_size_t = window.GetProperty("text: font size: text", 16);

var font_style_h0 = window.GetProperty(" text: font style: header 0", 0);
var font_style_h1 = window.GetProperty("text: font style: header 1", 0);
var font_style_h2 = window.GetProperty("text: font style: header 2", 1);
var font_style_t = window.GetProperty("text: font style: text", 1);

var min_font_size = window.GetProperty(" text: font size: min", 14);
var max_font_size = window.GetProperty(" text: font size: max", 36);

var text_shadow = window.GetProperty("text: shadow", true);

var h0_font, h1_font, h2_font, t_font, t2_font, tt_font;
get_font();

function get_font(){
    h0_font = gdi.Font(font_name_h0, font_size_h0, font_style_h0);
    h1_font = gdi.Font(font_name_h1, font_size_h1, font_style_h1);
    h2_font = gdi.Font(font_name_h2, font_size_h2, font_style_h2);
var font_style_c = font_style_t;                                      //
    if (font_style_t == 1){font_style_c = font_size_t > 18 ? 0 : 1;}  // Auto Change: Font Style VS Font Size
	t_font =  gdi.Font(font_name_t, font_size_t, font_style_c);
    t2_font = gdi.Font(font_name_t, font_size_t - 1, font_style_c);
    tt_font = gdi.Font(font_name_t, font_size_t, 1);
}

ColorTypeCUI = {
    text: 0,
    selection_text: 1,
    inactive_selection_text: 2,
    background: 3,
    selection_background: 4,
    inactive_selection_background: 5,
    active_item_frame: 6
};

ColorTypeDUI = {
	text: 0,
	background: 1,
	highlight: 2,
	selection: 3
};

function get_color(){
    try {
        if (window.InstanceType == 0){
            bg_color = window.GetColorCUI(ColorTypeCUI.background);
            h1_color = window.GetColorCUI(ColorTypeCUI.inactive_selection_text);
            h2_color = window.GetColorCUI(ColorTypeCUI.selection_background);
            t_color = window.GetColorCUI(ColorTypeCUI.text);
        } else if (window.InstanceType == 1) {
            bg_color = window.GetColorDUI(ColorTypeDUI.background);
            h1_color = window.GetColorDUI(ColorTypeDUI.highlight);
            h2_color = window.GetColorDUI(ColorTypeDUI.highlight);
            t_color = window.GetColorDUI(ColorTypeDUI.text);
        }
    } catch(e){};
    try {
        if (window.InstanceType == 0){
            bg_color = window.GetColourCUI(ColorTypeCUI.background);
            h1_color = window.GetColourCUI(ColorTypeCUI.inactive_selection_text);
            h2_color = window.GetColourCUI(ColorTypeCUI.selection_background);
            t_color = window.GetColourCUI(ColorTypeCUI.text);
        } else if (window.InstanceType == 1) {
            bg_color = window.GetColourDUI(ColorTypeDUI.background);
            h1_color = window.GetColourDUI(ColorTypeDUI.highlight);
            h2_color = window.GetColourDUI(ColorTypeDUI.highlight);
            t_color = window.GetColourDUI(ColorTypeDUI.text);
        }
    } catch(e){};
    window.Repaint();
}

var custom_colors = window.GetProperty(" colors: custom", false);

var c_bg_color = customColor(window.GetProperty(" color: background", "19-30-38"));
var c_h1_color = customColor(window.GetProperty(" color: header 1", "214-214-214"));
var c_h2_color = customColor(window.GetProperty(" color: header 2", "63-100-127"));
var c_t_color = customColor(window.GetProperty(" color: text", "160-160-160"));

get_color();
ini_color();						

function on_colors_changed(){						
    get_color();					
    ini_color();		
}

function ini_color(){							
    bg_color = custom_colors ? c_bg_color : bg_color;						
    h1_color = custom_colors ? c_h1_color : h1_color;
    h2_color = custom_colors ? c_h2_color : h2_color;
    t_color = custom_colors ? c_t_color : t_color;
}

function customColor(colour){						
   tmp = colour.split("-");					
   return (0xff000000 | (tmp[0]<<16) | (tmp[1]<<8) | (tmp[2]));						
}							

var colors_swap = window.GetProperty(" colors: swap", false);						
var tmp_h1_color = h1_color;
var tmp_h2_color = h2_color;
var tmp_t_color = t_color;

h1_color = !colors_swap ? tmp_h1_color : tmp_t_color;
h2_color = !colors_swap ? tmp_h2_color : tmp_h1_color;	
t_color = !colors_swap ? tmp_t_color : tmp_h1_color;
var color_selected_item = combineColors(bg_color, t_color)

var rc_arr = [".",  "/",  ":",  "*",  "?",  '"',  "<",  ">",  "|"];

window.GetProperty(".reserved characters: " + rc_arr[0] + "  replace by", "no char");   // "."
window.GetProperty(".reserved characters: " + rc_arr[1] + "  replace by", "-");         // "/"
window.GetProperty(".reserved characters: " + rc_arr[2] + "  replace by", "no char");   // ":"
window.GetProperty(".reserved characters: " + rc_arr[3] + "  replace by", "x");         // "*"
window.GetProperty(".reserved characters: " + rc_arr[4] + "  replace by", "no char");   // "?"
window.GetProperty(".reserved characters: " + rc_arr[5] + "  replace by", "''");        // '"'
window.GetProperty(".reserved characters: " + rc_arr[6] + "  replace by", "_");         // "<"
window.GetProperty(".reserved characters: " + rc_arr[7] + "  replace by", "_");         // ">"
window.GetProperty(".reserved characters: " + rc_arr[8] + "  replace by", "no char");   // "\"
//window.GetProperty(".reserved characters:  " + rc_arr[9] + "  replace by", "no char");

check_char_enter();

function check_char_enter() {
    for (var i = 0; i < rc_arr.length; i++) {
        tmp = window.GetProperty(".reserved characters: " + rc_arr[i] + "  replace by");
        tmp = tmp.length > 1 && tmp != "no char" && tmp != "space" ? tmp[0] : tmp;
        window.SetProperty(".reserved characters: " + rc_arr[i] + "  replace by", tmp);
        if (/[\.\/\:\*\?\"\<\>\|\\]/g.test(tmp) || tmp == ""){
            window.SetProperty(".reserved characters: " + rc_arr[i] + "  replace by", "no char");
        }
        if (tmp == " ") window.SetProperty(".reserved characters: " + rc_arr[i] + "  replace by", "space");
    }
}

function ch(i){
    var tmp = window.GetProperty(".reserved characters: " + rc_arr[i] + "  replace by");
    tmp = tmp == "no char" ? "" : tmp;
    tmp = tmp == "space" ? " " : tmp;
    return tmp;
}

function clean(n) {
    if (!n) return;
    var tmp = n.replace(/\./g,ch(0)).replace(/\//g,ch(1)).replace(/\:/g,ch(2)).replace(/\*/g,ch(3)).replace(/\?/g,ch(4)).replace(/\"/g,ch(5)).replace(/\</g,ch(6)).replace(/\>/g,ch(7)).replace(/\|/g,ch(8)).replace(/\\/g,"")
    return tmp.replace(/^\s+|\s+$/g,"").substr(0, 150);
}

function clean_ini(n){
    if (!n) return;
    return n.replace(/[\[\]вЂ™']/g, "");
}

function trim(n){
    if (!n) return;
    return n.replace(/^\s+|\s+$/g, "")
}

var fso = new ActiveXObject("Scripting.FileSystemObject");
var objShellApp = new ActiveXObject("Shell.Application");

var work_dir = window.GetProperty(" work directory", "tmp_Biography");
work_dir = clean(work_dir);
window.SetProperty(" work directory", work_dir);
if (!/\S/.test(work_dir)) {work_dir = "tmp_Biography"; window.SetProperty(" work directory", work_dir)};

//var work_path = fb.FoobarPath + clean(work_dir) + "\\";	
var work_path = fb.ProfilePath + clean(work_dir) + "\\";	

check_folder(work_path);

var script_path = work_path + "_download\\";
check_folder(script_path);
if (!fso.FileExists(script_path + "download.vbs")) {create_download_file()};

var doc = new ActiveXObject("htmlfile");
var WshShell = new ActiveXObject("WScript.Shell");
var vbs = "cscript //nologo \"" + script_path + "download.vbs\"";

var def_img;
var default_img_set = false;
var default_img = window.GetProperty("default img", false);
var default_img_path_bio = window.GetProperty(" default img path bio", ".\\themes\\DarkOne_v4.0\\Images\\DarkOne.png");
var default_img_path_album_review = window.GetProperty(" default img path album review", ".\\themes\\DarkOne_v4.0\\Images\\DarkOne.png");
var default_img_transparence = window.GetProperty(" default img transparence (0-255)", 255);
var fader_def_img = default_img_transparence;
try {
    var default_img_bio = resize_image(gdi.Image(default_img_path_bio));
    var default_img_album_review = resize_image(gdi.Image(default_img_path_album_review));
} catch(e) {};


var def_img_size;
default_img_ini();
var def_img_size_recount = true;

function default_img_ini() {
    if (data_main == 1 && data_other_idx == 3) {
        def_img = default_img_album_review;
    } else {
        def_img = default_img_bio;
    }
    def_img_size_recount = false;
}

var logo_img;
var logo_img_set = false;
var logo_img_idx = window.GetProperty("logo_img_idx", 3);
var logo_img_transparence = window.GetProperty(" logo img transparence (0-255)", 255);
var fader_logo = logo_img_transparence;
load_last_fm_logo();

var logo_img_path = [
    script_path + "footer_logo.png",
    script_path + "logo_sq_256_new_small.png",
    script_path + "logo_static.png",
    script_path + "logo.png",
    script_path + "logo 2.png"
]

var logo_img_dim = [
    [37, 37, 0, 0],
    [40, 40, 0, 0],
    [60, 60, 0, 0],
    [70, 70, 0, 70],
    [60, 60, 0, 0]
]

logo_img_ini();

function logo_img_ini(){
    logo_img = resize_logo_img(gdi.Image(logo_img_path[logo_img_idx]), logo_img_dim[logo_img_idx][0], logo_img_dim[logo_img_idx][1], logo_img_dim[logo_img_idx][2], logo_img_dim[logo_img_idx][3]);
}

function resize_logo_img(img, w, h, cx, cy){
    if (!img) return;

    var scale_w = w / img.Width;
    var scale_h = w / img.Height;

    var scale = Math.min(scale_w, scale_h);

    var iw = Math.round(img.Width * scale);
    var ih = Math.round(img.Height * scale);

    var temp_bmp = gdi.CreateImage(iw, ih);
    var temp_gr = temp_bmp.GetGraphics();
    temp_gr.SetSmoothingMode(2);
    temp_gr.SetInterpolationMode(7);
    temp_gr.DrawImage(img, 0, 0, iw, ih, cx, cy, img.width, img.height);
    temp_bmp.ReleaseGraphics(temp_gr);

    return temp_bmp;
    temp_bmp.Dispose();
    temp_gr = null;
    temp_bmp = null;
}

function default_fader_ini(){
    fader_logo = fade_effect ? 0 : logo_img_transparence;
    fader_def_img = fade_effect ? 0 : default_img_transparence;
}

/*
function artist_folder_path(n) {
    if (!n) return;
    return work_path + n;
}
*/

var save_images = window.GetProperty("save images", false);
var save_images_to_artist_folder = window.GetProperty("save to artist folder containing track", false);

function artist_folder_path(n) {
    if (!n || !metadb) return;

    if (metadb.RawPath.indexOf("file") < 0 || !save_images_to_artist_folder) {
        return work_path + n;
    }

    if (metadb.RawPath.indexOf("file") >= 0 && save_images_to_artist_folder) {
        var directory_path_arr = [], artist_path_arr = [], artist_path = "";
        directory_path_arr = directory_path.split("\\");

        for (var i = 0; i < directory_path_arr.length; i += 1) {
            if (directory_path_arr[i].toLowerCase().replace(/\s*/g, "").match(n.toLowerCase().replace(/\s*/g, ""))){
                artist_path_arr = directory_path_arr.slice(0, i + 1);
                break;
            }
        }

        artist_path = artist_path_arr.join("\\");
        
        if (fso.FolderExists(artist_path)) {
            return artist_path + "\\" + "lastFm";
        } else {
            return work_path + n;
        }
    }
}

function check_folder(n) {
    if (!n) return;
    try {
        if(!fso.FolderExists(n)) {fso.CreateFolder(n)};
    } catch(e) {}
}

function get_fnext(p) {
    if (!p) return;
    return p.replace(/.*\\/g,'');
}

var g_img = null;
var img_show = window.GetProperty("img show", true);
var img_size;
var img_size_recount = true;
var img_margin = window.GetProperty(" img: margin", 0);
var img_alignment = new Array("Adjust", "Adjust top - center", "Adjust top - left", "Centre", "Centre - top", "Stretch");
var img_alignment_idx = window.GetProperty("align mode", 1);
var img_selected = 0;
var on_img = false;
var img_file_names = [];
var images = [];
var no_img_msg = "";

var limit = window.GetProperty("img download limit", 6);
//if (!/\S/.test(limit) || limit <= 0) {limit = 6; window.SetProperty("img download limit", limit);}

var img_border = window.GetProperty("img border", false);
var img_border_width = window.GetProperty(" img border width", 2);
if (!/\S/.test(img_border_width) || img_border_width <= 0) {img_border_width = 1; window.SetProperty(" img border width", img_border_width);}
img_border_width = img_border ? window.GetProperty(" img border width") : 0;

var fader = 255;
var fade_effect = window.GetProperty("fade effect", true);

var quality_idx = window.GetProperty("download quality", 1);
var quality = [
    ["Low",    "avatar170s",   "avatar170s"],
    ["Medium", "ar0",          "500x500"],
    ["High",   "770x0",        ""]
];

var data_main = window.GetProperty("data_main: bio or album, similar", 0);
var data_other_idx = window.GetProperty("data_other_idx", 0);
var data_other = [
//  menu text,                  LastFm query                    file name(tooltip, INI data)
    ["Most popular albums",     "albums",                       "albums_popular"],      // 0
    ["Albums : release date",   "albums?order=release_date",    "albums_release_date"],
    ["Similar artists",         "similar",                      "similar"],
    ["Album : ",                "",                             "album"],
    ["Title : ",                "",                             "title"],
    ["Lyrics : ",               "",                             "lyrics"]
];

var scrollbar = window.GetProperty("Scrollbar", true);
var seekbar_x = 0;
var seekbar_y = 0;
var seekbar_w = window.GetProperty(" seekbar width ", 11);
var seekbar_min_h = 0;
var seekbar_h = 0;
var seekbar_k = 0;
var seekbar_posy = 0;
var on_seekbar = false;
var on_seekbar_down = false;
var on_scrollbar = false;
var on_scrollbar_down = false;
var wheel_id = 0;
var scroll_key_k = window.GetProperty(" scroll key k", 2);
if (!/\S/.test(scroll_key_k) || scroll_key_k < 0 || scroll_key_k >= 5) {scroll_key_k = 2; window.SetProperty(" scroll key k", scroll_key_k);}
scroll_key_k = 0;


var bg_transparence = window.GetProperty("text bg transparence (0-255)", 220);
var t_margin = window.GetProperty(" text: margin", 5);
var txt_x = window.GetProperty("txt_x", 0);
var old_txt_x = 0;
var txt_y = window.GetProperty("txt_y", Math.round(window.Height / 2));
var delta_x, delta_y;
var h1_y = 0, h2_y = 0, t_y = 0, t_x = 0;

var search_by = ["%artist%", "%album artist%", "%remixed by%"];
var search_by_idx = window.GetProperty("search by idx", 0);

var refresh_data = false;
var lock_loading = false;
var history_arr = [];
var history_seach = ""
var history_show = false;

var history_file_path = script_path + "history.txt";

var complete_path, directory_path;
var meta_artist = "", old_artist = "", lock_artist = "";
var meta_album = "", old_album = "", lock_album = "";
var meta_title = "", old_title = "", lock_title = "";
var artist_folder_path_old = "";
var request_counter = 0;

var text = "";
var header_0 = "";	
var header_1 = "";
var header_2 = "";

var text_array = [];
var text_height = 0;
var text_row_width = 0;
var text_row_height = 0;
var text_rows = 0;
var text_visable_rows = 0;
var text_visable_height = 0;

var h0_text_array = [];
var h0_text_row_height = 0;
var h0_text_visable_rows = 0;

var h1_char_width = 0;
var h1_text_array = [];
var h1_text_row_height = 0;
var h1_text_visable_rows = 0;

var h2_text_array = [];
var h2_text_row_height = 0;
var h2_text_visable_rows = 0;

var info_text_arr = [];
var info_text_color = [];
var info_text_color_arr = [];
var info_text_font = [];
var info_text_font_arr = [];

var info_text_0 = window.GetProperty("info text 0", true);
var info_text_1 = window.GetProperty("info text 1", true);
var info_text_2 = window.GetProperty("info text 2", true);
var info_text_3 = window.GetProperty("info text 3", false);
var info_text_4 = window.GetProperty("info text 4", true);
var info_text_5 = window.GetProperty("info text 5", true);
var info_text_6 = window.GetProperty("info text 6", true);
var info_text_show = window.GetProperty("info text " + (data_main == 0 ? 0 : data_main + data_other_idx));
var info_text_btn_transparence = window.GetProperty(" infotext btn transparence (0-255)", 200);

var on_text = false;
var on_header_0 = false;
var on_header_1 = false;
var on_header_2 = false;
var on_text_down = false;
var on_info_text_btn = false;
var refresh_txt = true;
var text_hiden = window.GetProperty("txt hiden", false);

var tooltip_on = false;
var tooltip_delay = window.GetProperty(" tooltip delay (ms)", 2000);
if (!/\S/.test(tooltip_delay) || tooltip_delay < 1){tooltip_delay = 2000; window.SetProperty(" tooltip delay (ms)", tooltip_delay)};
var tooltip = window.GetProperty(" tooltip", true); 
var tooltip_text = "";
var pos_x = 0, pos_y = 0;
var tooltip_x = 0, pos_y = 0;

var text_idx = 0;
var selected_item = "";
var selected_item_rows = [];
var selected_item_rows_tmp = [];
var popular_this_week = "";
var latest_release = "";

var external_links = [];

var language_text = [
    ["en", "English",   "Text not found"],
    ["it", "Italian",   "Testo non trovato"],
    ["zh", "Chinese",   ". . ."],
    ["de", "German",    "Text nicht gefunden"],
    ["pl", "Polish",    "Nie znaleziono tekstu"],
    ["pt", "Portuguese",". . ."],
    ["ru", "Russian",   ". . ."],
    ["tr", "Turkish",   ". . ."],
    ["fr", "French",    "Texte non trouvГ©"],
    ["sv", "Swedish",   ". . ."],
    ["ja", "Japanese",  ". . ."]
]

window.GetProperty("en", true);
window.GetProperty("it", false);
window.GetProperty("zh", false);
window.GetProperty("de", false);
window.GetProperty("pl", false);
window.GetProperty("pt", false);
window.GetProperty("ru", true);
window.GetProperty("tr", false);
window.GetProperty("fr", false);
window.GetProperty("sv", false);
window.GetProperty("ja", false);

var lang_idx = window.GetProperty("lang", 0);
var tmp_lang_idx;
var lang_arr = [];
create_lang_arr();

function create_lang_arr(){ 
    lang_arr = [];
    for (var i = 0; i < language_text.length; i++) {
        if (window.GetProperty(language_text[i][0]) == true){
            lang_arr.push(language_text[i][0]);
        }
    }

    if (lang_idx >= lang_arr.length) {
        lang_idx = lang_idx - 1 <= 0 ? 0 : lang_idx - 1;
        window.SetProperty("lang", lang_idx);
    }

    if (lang_idx < lang_arr.length) {
        var i = 0;
        do {
            if (tmp_lang_idx == lang_arr[i]) {
                lang_idx = i;
                window.SetProperty("lang", lang_idx);
            }
            i++;
        } while (i < lang_arr.length);
    }

    if (lang_arr.length == 1){
        tmp_lang = lang_arr[0];
    }

    if (lang_arr.length == 0){
        lang_arr.push(tmp_lang);
        window.SetProperty(tmp_lang, true);
        get_text();
    }
}

function lang_query(i){
    return lang_arr[i] == "en" ? "" : lang_arr[i] + "/";;
}

function get_text_nf(n) {
    tmp = "";
    var j = 0;
    do {
        if (language_text[j][0] == n) {
            tmp = language_text[j][2];
        }
        j++;
    } while (j < language_text.length);
    return tmp;
}

function get_text_menu(n) {
    tmp = "";
    var j = 0;
    do {
        if (language_text[j][0] == n) {
            tmp = language_text[j][1];
        }
        j++;
    } while (j < language_text.length);
    return tmp;
}

var remap_data = window.GetProperty(" remap artist", "ALLMAN BROTHERS BAND:THE ALLMAN BROTHERS BAND;");
if (!/\S/.test(remap_data)) {remap_data = "ALLMAN BROTHERS BAND:THE ALLMAN BROTHERS BAND;"; window.SetProperty(" remap artist", remap_data)};
var remap_arr = [];
remap_arr = remap_data.split(/[:;]/g);

function remap_artist(n){
    if (!n) return;
    var tmp = "";
    for (var i = 0; i < remap_arr.length; i += 2) {
        if (remap_arr[i] == n) tmp = remap_arr[i + 1];
    }
    return tmp ? tmp : n;
}

var cycle_txt_y = 20;
var cycle_set = false;
var cycle_timer, cycle_step = 0;
var cycle = window.GetProperty("auto cycle (sec)", 60);
if (cycle > 0) cycle_set_timer();

var delay = false;
var get_files_timer, ftimer, ftimer_logo, ftimer_def_img, tooltip_timer;

var upload_delay_time = window.GetProperty("upload delay: time (ms)", 500); 

var panel_on = true;

var selection_mode = window.GetProperty("selection mode", 0);
var metadb;
on_item_focus_change();

function on_paint(gr){
   !window.IsTransparent && gr.FillSolidRect(0, 0, ww, wh, bg_color);

    draw_image(gr);
 
    if (!meta_artist){
        text_shadow && gr.GdiDrawText( "No artist selected", gdi.Font(font_name_h1,font_size_h1, font_style_h1), bg_color, 0 + 1, 0 + 2, ww, wh, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_WORD_ELLIPSIS ); 
        gr.GdiDrawText( "No artist selected", gdi.Font(font_name_h1,font_size_h1, font_style_h1), h1_color, 0, 0, ww, wh, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_WORD_ELLIPSIS ); 
    }

    if (cycle_set && on_img){   
        gr.FillSolidRect(0, 0, ww, wh, RGBA(getRed(bg_color), getGreen(bg_color), getBlue(bg_color), bg_transparence));   
        var txt_cycle = cycle == 0 ? "off" : cycle + " sec";
        text_shadow && gr.GdiDrawText("AUTO CYCLE:   " + txt_cycle, t_font, bg_color, 0 + 1, cycle_txt_y + 2, ww, wh, DT_CENTER | DT_WORD_ELLIPSIS );
        gr.GdiDrawText("AUTO CYCLE:   " + txt_cycle, t_font, t_color, 0, cycle_txt_y, ww, wh, DT_CENTER | DT_WORD_ELLIPSIS );
    } else {
        if (meta_artist || history_show) gr.FillSolidRect(txt_x, txt_y, ww - txt_x, wh - txt_y, RGBA(getRed(bg_color), getGreen(bg_color), getBlue(bg_color), bg_transparence));
    }

    draw_seekbar(gr);

    if (lock_loading){
        for (var i = 0; i < h0_text_visable_rows; i += 1) {     // header_0
            try {
                color = on_header_0 || on_header_1 ? t_color : h1_color;

                text_shadow && gr.GdiDrawText( h0_text_array[i], h0_font, bg_color, t_x + 1, h0_y + h0_text_row_height * i + 2, text_row_width, wh, text_alignment[text_alignment_h0][1] );
                gr.GdiDrawText( h0_text_array[i], h0_font, color, t_x, h0_y + h0_text_row_height * i, text_row_width, wh, text_alignment[text_alignment_h0][1] );
            } catch(e) {}
        }
    }

    for (var i = 0; i < h1_text_visable_rows; i += 1) {     // header_1
        try {
            font = !history_show ? h1_font : t_font;

            text_shadow && gr.GdiDrawText( h1_text_array[i], font, bg_color, t_x + 1, h1_y + h1_text_row_height * i + 2, text_row_width, wh, text_alignment[text_alignment_h1][1] );
            gr.GdiDrawText( h1_text_array[i], font, h1_color, t_x, h1_y + h1_text_row_height * i, text_row_width, wh, text_alignment[text_alignment_h1][1] );
        } catch(e) {}
    }

    if (meta_artist){
        l_x1 = t_x;
        l_y1 = h1_y + h1_text_row_height * h1_text_array.length + 2;
        l_x2 = t_x + text_row_width;
        l_y2 = h1_y + h1_text_row_height * h1_text_array.length + 2;
        l_color = RGBA(getRed(h1_color), getGreen(h1_color), getBlue(h1_color), 120);
        gr.DrawLine(l_x1, l_y1, l_x2, l_y2, 1, l_color);

        if (text_shadow){
            l_color_2 = RGBA(getRed(bg_color), getGreen(bg_color), getBlue(bg_color), 255);
            gr.DrawLine(l_x1, l_y1 + 1, l_x2, l_y2 + 1, 1, l_color_2);
        }
    }

    if (on_info_text_btn && info_text_arr.length > 0) draw_info_text_btn(gr, t_x + text_row_width / 2, t_y - text_row_height / 2);

    if (data_main == 0){
        for (var i = 0; i < h2_text_visable_rows; i += 1) {     // header_2
            try {
                text_shadow && gr.GdiDrawText( h2_text_array[i], t2_font, bg_color, t_x + 1, h2_y + h2_text_row_height * i + 2, text_row_width, wh, text_alignment[text_alignment_h2][1] );
                gr.GdiDrawText( h2_text_array[i], t2_font, h1_color, t_x, Math.round(h2_y + h2_text_row_height * i), text_row_width, wh, text_alignment[text_alignment_h2][1] );
            } catch(e) {}
        }
    }

    if (data_main == 1){
        for (var i = 0; i < h2_text_visable_rows; i += 1) {     // header_2
            try {
                text_shadow && gr.GdiDrawText( h2_text_array[i], h2_font, bg_color, t_x + 1, h2_y + h2_text_row_height * i + 2, text_row_width, wh, text_alignment[text_alignment_h2][1] );
                gr.GdiDrawText( h2_text_array[i], h2_font, h1_color, t_x, Math.round(h2_y + h2_text_row_height * i), text_row_width, wh, text_alignment[text_alignment_h2][1] );
            } catch(e) {}
        }
    }

    for (var i = 0; i < text_array.length; i += 2) {    // text
        try {
            row = t_y + (i * text_row_height / 2) + scroll_;

            color = info_text_color_arr[i]? info_text_color_arr[i] : t_color;
            font = info_text_font_arr[i] ? info_text_font_arr[i]:  t_font;

            if (data_main == 0 || history_show) {
                var j = 0;
                do {
                    if (selected_item_rows[j] == i / 2){
                    color = color_selected_item;
                }
                j++;
                } while (j < selected_item_rows.length);
            }

            if (row > t_y - text_row_height * 0.5  && row < t_y + text_visable_height){  //// 0.5
                if (row > t_y + text_visable_height - text_row_height){
                    dh = Math.ceil(scroll_ * -1 / text_row_height) * text_row_height - scroll_ * -1;
                } else {
                    dh = 0;
                }

                text_shadow && gr.GdiDrawText( trim(text_array[i]), font, bg_color, t_x + 1, row + 2, text_row_width, text_row_height - dh, text_alignment[text_alignment_t][1] );
                gr.GdiDrawText( trim(text_array[i]), font, color, t_x, row, text_row_width, text_row_height - dh, text_alignment[text_alignment_t][1] );

            }
        } catch(e) {}
    }

    tooltip_on && draw_tooltip(gr);
}

function draw_image(gr){
    if (g_img && img_show){
        if (!img_size_recount){
            img_size = calc_img_size(g_img);
            img_size_recount = true;
        }

        gr.DrawImage(g_img, img_size.x, img_size.y, img_size.width, img_size.height, img_size.cx, img_size.cy, img_size.cwidth, img_size.cheight, 0, fader);
        img_border && gr.DrawRect( img_size.x - img_border_width /2, img_size.y - img_border_width /2, img_size.width + img_border_width, img_size.height + img_border_width, img_border_width, RGBA(getRed(t_color), getGreen(t_color), getBlue(t_color), fader));
        lw = 1;
        img_border && gr.DrawRect(img_size.x + lw / 2, img_size.y + lw / 2, img_size.width - lw, img_size.height - lw, lw, RGBA(getRed(bg_color), getGreen(bg_color), getBlue(bg_color), fader - 200 <= 0 ? 0 : fader - 200));
    }

    if ((!g_img && (!default_img && !default_img_set) && logo_img && img_show) || logo_img_set){
        if (fader_logo == 0 && fade_effect) fader_timer_logo_on();

        gr.DrawImage(logo_img, 5, 5, logo_img.Width, logo_img.Height, 0, 0, logo_img.Width, logo_img.Height, 0, fader_logo);
    }

    if ((!g_img && default_img && def_img && img_show) || default_img_set){
        if (!def_img_size_recount){
            def_img_size = calc_img_size(def_img);
            def_img_size_recount = true;
        }

        if (fader_def_img == 0 && fade_effect) fader_timer_def_img_on();

        def_img && gr.DrawImage(def_img, def_img_size.x, def_img_size.y, def_img_size.width, def_img_size.height, def_img_size.cx, def_img_size.cy, def_img_size.cwidth, def_img_size.cheight, 0, fader_def_img);
        img_border && gr.DrawRect( def_img_size.x - img_border_width /2, def_img_size.y - img_border_width /2, def_img_size.width + img_border_width, def_img_size.height + img_border_width,  img_border_width, RGBA(getRed(t_color), getGreen(t_color), getBlue(t_color), fader_def_img));
    }
}

function draw_seekbar(gr){
    seekbar_x = (text_height > text_visable_height && scrollbar) ? ww - t_margin - seekbar_w - 10 : ww;
    seekbar_y = t_y + (scroll_ * -1) / text_row_height * seekbar_k;
    seekbar_min_h = text_visable_height > 0 ? 6 : 0;
    seekbar_h = text_visable_height * (text_visable_rows / text_rows) + seekbar_min_h;

    if (scrollbar && text_height > text_visable_height){
        gr.SetSmoothingMode(2);
        seekbar_alpha = (on_seekbar || on_seekbar_down || on_scrollbar) && !on_text_down ? 255 : 120;
   var  theme_color = (window.InstanceType == 1) ? h1_color : h2_color;                                                                // Theme color scrollbar         
        seekbar_color_bg = RGBA(getRed(theme_color), getGreen(theme_color), getBlue(theme_color), seekbar_alpha / 4);
        seekbar_color = RGBA(getRed(theme_color), getGreen(theme_color), getBlue(theme_color), seekbar_alpha);
        gr.FillSolidRect(seekbar_x + 10, t_y - seekbar_min_h / 2, seekbar_w, text_visable_height + seekbar_min_h, seekbar_color_bg);   // Scrollbar background
        gr.FillSolidRect(seekbar_x + 10, seekbar_y - seekbar_min_h / 2, seekbar_w, seekbar_h, seekbar_color);
    }
}

function draw_info_text_btn(gr, x, y){
    var x = t_x + text_row_width / 2;
    var y = t_y - text_row_height / 2;
    var d = 8;
    var color = RGBA(getRed(h1_color), getGreen(h1_color), getBlue(h1_color), info_text_btn_transparence);
    var color2 = RGBA(getRed(bg_color), getGreen(bg_color), getBlue(bg_color), info_text_btn_transparence);

    var show = info_text_show ? 0 : 1;
    var radius = d / 2;
    var points = [];
    var steps = 6;

    for (var i = 0; i < steps; i++) {
        if (i % 2 == show) {
            points.push(x + (radius * Math.cos(Math.PI * i / steps * 2 - Math.PI / 2)));
            points.push(y - 1 + (radius * Math.sin(Math.PI * i / steps * 2 - Math.PI / 2)));
        }
    }

    gr.SetSmoothingMode(2);
    if (text_visable_rows > 0){
        gr.DrawPolygon(color2, 1, points);
        gr.FillPolygon(color, 1, points);
    }
}

function draw_tooltip(gr){
    tt = tooltip_text;

    tt_w = gr.CalcTextWidth(tt, tt_font) + 12;
    tt_h = gr.CalcTextHeight(tt, tt_font) + 2;
    tt_x = tooltip_x - tt_w * 0.5;
    tt_x = tt_x <= 10 ? 10 : (tt_x >= ww - tt_w - 10 ? ww - tt_w - 10 : tt_x);
    tt_y = tooltip_y - tt_h - 8;
    tt_y = tt_y <= 10 ? 10 : tt_y;

    gr.FillSolidRect(tt_x, tt_y, tt_w, tt_h, t_color);
    gr.DrawRect(tt_x, tt_y, tt_w, tt_h, 1, bg_color);
    gr.GdiDrawText( tt, tt_font, bg_color, tt_x, tt_y, tt_w, tt_h, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
}

function on_playlist_switch() {
    on_item_focus_change();
}

function on_playback_new_track() {
    on_item_focus_change();
}

function on_playback_dynamic_info_track() {
    on_item_focus_change();
}

function on_playback_stop() {
    on_item_focus_change();
}

function on_selection_changed(metadb) {
   on_item_focus_change();
}

function on_item_focus_change() {
    switch (selection_mode) {
    case 0:
        metadb = fb.IsPlaying ? fb.GetNowPlaying() : fb.GetFocusItem();   
        break;   
    case 1:   
        metadb = fb.GetFocusItem();
        break;   
    } 

    if (metadb) on_metadb_changed();  
}   

function Eval(field) {   
    if (!metadb) return;   
    complete_path = fb.Titleformat("%path%").EvalWithMetadb(metadb);
    directory_path = fb.Titleformat("$directory_path(%path%)").EvalWithMetadb(metadb); 
    return complete_path.indexOf('://') > 0 ? fb.TitleFormat("[" + field + "]").Eval(true) : fb.TitleFormat("[" + field + "]").EvalWithMetadb(metadb);
} 

function on_metadb_changed(handles, fromhook) {
    if (!panel_on) return; 
    if (!metadb) return; 
    
    ini_data();

    if (refresh_data){
        del_folder(artist_folder_path(clean(meta_artist)));
        old_artist = "";
        old_album = "";
        old_title = "";
        refresh_data = false;
    }
    
    if (meta_artist != old_artist){
        
        write_history(meta_artist);
        
        delete_empty_folders();
        check_folder(artist_folder_path(clean(meta_artist)));
        
        //if (!save_images) del_folders(clean(meta_artist));	
        
        if (!save_images) {
            if (!save_images_to_artist_folder){
                del_folders(clean(meta_artist));
            }
            if (save_images_to_artist_folder){
                del_folder(artist_folder_path_old);
            }
        }
        
        if (data_main == 0 || data_main == 1 && data_other_idx == 0 || data_main == 1 && data_other_idx == 1 || data_main == 1 && data_other_idx == 2){
            get_img(meta_artist, meta_album, meta_title);
            old_artist = meta_artist;
        }
        
        artist_folder_path_old = artist_folder_path(clean(meta_artist));
    }

    if (meta_album && meta_album != old_album && data_main == 1 && data_other_idx == 3) {
        get_img(meta_artist, meta_album, meta_title);	
        old_album = meta_album;
    }

    if (meta_title && meta_title != old_title && data_main == 1 && (data_other_idx == 4 || data_other_idx == 5)) {
        get_img(meta_artist, meta_album, meta_title);	
        old_title = meta_title;
    }
} 

function ini_data(){
    search = search_by_idx == 2 ? "$if3(%remixed by%, %album artist%, %artist%)" : search_by[search_by_idx];
    meta_artist = Eval(search);
    meta_album = Eval('%album%');
    meta_title = Eval('%title%');

    meta_artist = meta_artist ? trim(remap_artist(meta_artist)) : "";
    meta_album = meta_album ? trim(meta_album) : "";
    meta_title = meta_title ? trim(meta_title) : "";
    
    if (lock_loading){
        meta_artist = lock_artist;
        meta_album = lock_album;
        meta_title = lock_title;
    }
}

function clear_img_var(){
    if (g_img) g_img.Dispose();
    g_img = null;    
    images = [];			
    img_file_names = [];			
    img_selected = 0;
    no_img_msg = "";  
}

function get_img(t_artist, t_album, t_title) {
    path = artist_folder_path(clean(t_artist));
    
    clear_img_var();
    clear_txt_var();
    					
    if (fso.FolderExists(path)){	
        get_img_from_dir(path, t_artist, t_album, t_title);

        if (!g_img && images.length > 0) {
            next_image(0); 
            get_text(path, t_artist, t_album, t_title);
        } else {	
            switch(data_main) {						
	        case 0:	
                get_lastFm_meta_artist_img(path, t_artist);
                break;						
	        case 1:					
                switch(data_other_idx) {						
                case 0:						
                case 1:	
                    get_lastFm_album_img(path, t_artist);
                    break;						
                case 2:						
                    get_lastFm_similar_img(path, t_artist);
                    break;	
                case 3:	
                    t_album && get_lastFm_meta_album_img(path, t_artist, t_album);
                    break;
                case 4:	
                case 5:	
                    t_title && get_lastFm_meta_title_img(path, t_artist, t_album, t_title);
                    break;
                }						
                break;						
            }						
        } 
    }						
}
        
function get_img_from_dir(path, t_artist, t_album, t_title) {
    if (!t_artist) return;
    if (!t_album && data_main == 1 && data_other_idx == 3) return;    
    if (!t_title && data_main == 1 && data_other_idx == 4) return;
    if (!t_title && data_main == 1 && data_other_idx == 5) return;   

    t_artist = t_artist ? clean(t_artist) : "";
    t_album = t_album ? clean(t_album) : "";
    t_title = t_title ? clean(t_title) : ""; 

    switch(data_main) {						
    case 0:	
        img_file_names = utils.Glob( path + "\\" + t_artist + "*" + "artist.jpg").toArray();
        img_file_names = naturalSort(img_file_names);	        
        break;						
    case 1:	
        switch(data_other_idx) {						
        case 0:						
        case 1:	
            img_file_names = [];  
            for (var i = 0; i < limit; i++) { 
                var album = utils.ReadINI( path + "\\" + t_artist + "_album_info.ini", data_other[data_other_idx][2] + " : name" , i );				
                album && img_file_names.push(path + "\\" + t_artist + "_" + clean(album) + ".jpg");
            }
            break;	
        case 2:	
            img_file_names = utils.Glob( path + "\\" + t_artist + "*" + data_other[data_other_idx][2] + ".jpg").toArray();
            img_file_names = naturalSort(img_file_names);	            
            break;	
        case 3:	
            img_file_names = utils.Glob( path + "\\" + t_artist + "_" + t_album.replace(/[.вЂ™']/g, "*") + ".jpg").toArray();	
            break;
        case 4:
        case 5:
            var album = utils.ReadINI( path + "\\" + t_artist + "_title_info.ini", clean_ini(t_title), "album");
            img_file_names = utils.Glob( path + "\\" + t_artist + "_" + album + ".jpg").toArray();	
            break;
        }
        break;        
    }
    
    if (img_file_names.length > images.length){
        images = [];

        var i = 0;
        do {
            var tmp;
            try {	
                tmp = resize_image(gdi.Image(img_file_names[i]))
                if (typeof tmp == 'object' ) {
                    images.push(tmp);
                }
            } catch(e) {}
            i++;
        } while (i < img_file_names.length); 
    }
    
    if (images.length == 0){
        default_img_ini();
    }
    
    if (cycle_timer) cycle_step = 0;
}	

function next_image(d){
    fader = fade_effect ? 0 : 255;
    default_fader_ini();
    
    if (d < 0) {img_selected = img_selected <= 0 ? images.length - 1 : img_selected = img_selected - 1};
    if (d > 0) {img_selected = img_selected >= images.length - 1 ? 0 : img_selected = img_selected + 1};
    
    g_img = images[img_selected];
    img_size_recount = false;

    window.Repaint();
    if (g_img && fade_effect) fader_timer();
}

function resize_image(img){
    if (!img || !ww || !wh) return;
    
    var scale_w = ww / img.Width;
    var scale_h = wh / img.Height;
    
    if (img_alignment_idx == 0 || img_alignment_idx == 1 || img_alignment_idx == 2){
        var scale = Math.min(scale_w, scale_h);
    } else {
        var scale = Math.max(scale_w, scale_h);
    }

    var iw = Math.round(img.Width * scale);
    var ih = Math.round(img.Height * scale)

    return img.Resize(iw, ih, 7);
    img && img.Dispose();
    img = null;
}

function clear_txt_var() {
    header_2 = "";
    text = "";
    text_array = [];
    scroll = 0;
    scroll_ = 0, scroll__ = 0, scroll___ = 0;
    info_text_arr = [];
    info_text_color = [];
    info_text_font = [];
    get_text_array();
    popular_this_week = "";
    latest_release = "";
    external_links = [];
    history_arr = [];
}

function get_text(path, t_artist, t_album, t_title){
    clear_txt_var();
    
    switch(data_main) {
    case 0:
        get_bio_text(path, t_artist);
        break;
    case 1:
        switch(data_other_idx) {
        case 0:
        case 1:
            get_album_text(img_selected, path, t_artist)
            break;
        case 2:
            get_similar_text(img_selected, path, t_artist);
            break;
        case 3:
            get_meta_album_text(path, t_artist, t_album);
            break;
        case 4:
            get_meta_title_text(path, t_artist, t_album, t_title);
            break;
        case 5:
            get_meta_lyrics_text(path, t_artist, t_album, t_title);
            break;
        }
        break;
    }
    
    get_external_links(path, t_artist); 
}

function get_bio_text(path, t_artist) {
    refresh_txt = true;
    
    var txt_file = path + "\\" + clean(t_artist) + "_biography_" + lang_arr[lang_idx] + ".txt";
    header_2 = utils.ReadINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)) + " : years active", lang_arr[lang_idx]);  
    
    info_text_arr = get_info_text("", path, t_artist);
    info_text_color = get_info_text_color("", path, t_artist);
    info_text_font = get_info_text_font("", path, t_artist);
    
    popular_this_week = utils.ReadINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), "popular_this_week");
    latest_release = utils.ReadINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), "latest_release");

    if (info_text_arr.length == 0 && request_counter <= 1) {
        get_lastFm_artist_info_text(path, "file", t_artist);
    } else {
        if (fso.FileExists(txt_file)){
            read_txt_file(txt_file);
        } else {
            get_lastFm_bio_text(path, txt_file, t_artist);	
        }				
        request_counter = 0;
    }
    request_counter++;
}				

function get_album_text(s, path, t_artist) {			
    refresh_txt = true;	

    var album = utils.ReadINI( path + "\\" + clean(t_artist) + "_album_info.ini", data_other[data_other_idx][2] + " : name" , s );				
    var txt_file = path + "\\" + clean(t_artist) + "_" + clean(album) + "_" + lang_arr[lang_idx] + ".txt";   
    header_2 = album;				

    info_text_arr = get_info_text(s, path, t_artist);	
    info_text_color = get_info_text_color(s, path, t_artist);
    info_text_font = get_info_text_font(s, path, t_artist);

    if (info_text_arr.length == 0 && request_counter <= 1) {
        get_lastFm_album_img(path, t_artist);				
    } else {
        if (fso.FileExists(txt_file)){			
            read_txt_file(txt_file);			
        } else {	
            get_lastFm_album_text(path, txt_file, album ? t_artist : "", album);
        }
        request_counter = 0;        
    }
    request_counter++;
}

function get_similar_text(s, path, t_artist) {
    refresh_txt = true;
    
    var txt_file = path + "\\" + clean(t_artist) + "_" + s + "_" +  data_other[data_other_idx][2] + "_" + lang_arr[lang_idx] + ".txt";   
    var similar_artist = utils.ReadINI( path + "\\" + clean(t_artist) + "_artist_info.ini", data_other[data_other_idx][2] + " : name" , s );
    header_2 = similar_artist;

    if (!similar_artist && request_counter <= 1) {
        get_lastFm_similar_img(path, t_artist);
    } else {
        if (fso.FileExists(txt_file)){
            read_txt_file(txt_file);
        } else {
            get_lastFm_bio_text(path, txt_file, similar_artist);  
        }
        request_counter = 0;  
    }
    request_counter++;
}

function get_meta_album_text(path, t_artist, t_album) {			
    refresh_txt = true;				

    var txt_file = path + "\\" + clean(t_artist) + "_" + clean(t_album) + "_" + lang_arr[lang_idx] + ".txt";   
    var album = t_album;				
    header_2 = album;

    info_text_arr = get_info_text("", path, t_artist, t_album);
    info_text_color = get_info_text_color("", path, t_artist, t_album);
    info_text_font = get_info_text_font("", path, t_artist, t_album);

    if (info_text_arr.length == 0 && request_counter <= 1) {	
        get_lastFm_meta_album_img(path, t_artist, album);
    } else {			
        if (fso.FileExists(txt_file)){			
            read_txt_file(txt_file);			
        } else {			
            get_lastFm_album_text(path, txt_file, t_artist, album);
        }	
        request_counter = 0;    		
    }
    request_counter++;
}

function get_meta_title_text(path, t_artist, t_album, t_title) {	
    refresh_txt = true;				

    var txt_file = path + "\\" + "title_" + clean(t_title) + "_" + lang_arr[lang_idx] + ".txt";   				
    var title = t_title;				
    header_2 = title;				
			
    info_text_arr = get_info_text("", path, t_artist, t_album, t_title);
    info_text_color = get_info_text_color("", path, t_artist, t_album, t_title);
    info_text_font = get_info_text_font("", path, t_artist, t_album, t_title);

    if (info_text_arr.length == 0 && request_counter <= 1) {	
        get_lastFm_meta_title_img(path, t_artist, "", title);
    } else {			
        if (fso.FileExists(txt_file)){			
            read_txt_file(txt_file);			
        } else {			
            get_lastFm_meta_title_text(path, txt_file, t_artist, t_album, title);
        }	
        request_counter = 0;    		
    }
    request_counter++;
}

function get_meta_lyrics_text(path, t_artist, t_album, t_title) {	
    refresh_txt = true;				

    var txt_file = path + "\\" + "lyrics_" + clean(t_title) + ".txt";   				
    var title = t_title;				
    header_2 = title;

    var lyrics_url = utils.ReadINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "LastFm_lyrics_url");
    info_text_arr = get_info_text("", path, t_artist, t_album, t_title);
    info_text_color = get_info_text_color("", path, t_artist, t_album, t_title);
    info_text_font = get_info_text_font("", path, t_artist, t_album, t_title);

    if (fso.FileExists(txt_file)){	
        read_txt_file(txt_file);			
    } else {
        //if (lyrics_url){
            ///get_metrolyrics_lyrics_text(path, txt_file, lyrics_url, t_artist, title);
            get_metrolyrics_meta_lyrics_text(path, txt_file, t_artist, title);
        //} else {
        //    get_azlyrics_meta_lyrics_text(path, txt_file, t_artist, title);
        //}
    }	
}

function get_info_text(s, path, t_artist, t_album, t_title) {
    switch(data_main) {
    case 0:
        var text_rank = utils.ReadINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx] + "_rank");  
        var text = utils.ReadINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx]); 
        break;
    case 1:
        switch(data_other_idx) {
        case 0:
        case 1:
            var text = utils.ReadINI( path + "\\" + clean(t_artist) + "_album_info.ini", data_other[data_other_idx][2] + " : info : " + lang_arr[lang_idx], s ); 
            break;
        case 2:
            //     
            break;
        case 3:
            var text = utils.ReadINI( path + "\\" + clean(t_artist) + "_album_info.ini", clean_ini(clean(t_album)), lang_arr[lang_idx]);  
            break;
        case 4:
            var text = utils.ReadINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), lang_arr[lang_idx]); 
            break;
        case 5:
            var text = utils.ReadINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "lyrics");  
            break;
        }
    }

    text = text_rank ? text_rank + text : text;
    return (text ? text.replace(/\*+$/g, "").split("*") : []); 
}

function get_info_text_color(s, path, t_artist, t_album, t_title) {
    switch(data_main) {
    case 0:
        var color_rank = utils.ReadINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx] + "_rank_c"); 
        var color = utils.ReadINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx] + "_c"); 
        break;
    case 1:
        switch(data_other_idx) {
        case 0:
        case 1:
            var color = utils.ReadINI( path + "\\" + clean(t_artist) + "_album_info.ini", data_other[data_other_idx][2] + " : info : " + lang_arr[lang_idx], s + "_c");
            break;
        case 2:
            //
            break;
        case 3:
            var color = utils.ReadINI( path + "\\" + clean(t_artist) + "_album_info.ini", clean_ini(clean(t_album)), lang_arr[lang_idx] + "_c");  
            break;
        case 4:
            var color = utils.ReadINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), lang_arr[lang_idx] + "_c");  
            break;
        case 5:
            var color = utils.ReadINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "lyrics_c");  
            break;
        }
    }

    color = color_rank ? color_rank + color : color;
    return (color ? color.replace(/\*+$/g, "").split("*") : []); 
}

function get_info_text_font(s, path, t_artist, t_album, t_title) {
    switch(data_main) {
    case 0:
        var font_rank = utils.ReadINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx] + "_rank_f"); 
        var font = utils.ReadINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx] + "_f"); 
        break;
    case 1:
        switch(data_other_idx) {
        case 0:
        case 1:
            var font = utils.ReadINI( path + "\\" + clean(t_artist) + "_album_info.ini", data_other[data_other_idx][2] + " : info : " + lang_arr[lang_idx], s + "_f");
            break;
        case 2:
            //
            break;
        case 3:
            var font = utils.ReadINI( path + "\\" + clean(t_artist) + "_album_info.ini", clean_ini(clean(t_album)), lang_arr[lang_idx] + "_f");  
            break;
        case 4:
            var font = utils.ReadINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), lang_arr[lang_idx] + "_f");  
            break;
        case 5:
            var font = utils.ReadINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "lyrics_f");  
            break;
        }
    }

    font = font_rank ? font_rank + font : font;
    return (font ? font.replace(/\*+$/g, "").split("*") : []); 
}

function get_external_links(path, t_artist) {
    var info_external_links = utils.ReadINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(t_artist), "external_links");
    external_links = info_external_links ? info_external_links.split("*") : []; 

    if (external_links.length == 0) get_artist_external_links(path, t_artist);
}

function read_txt_file(file){
    if (!file) return; 
    text = utils.ReadTextFile(file);
    get_text_array();
}

function get_text_array() {
    t_x = txt_x + t_margin;

    text_row_width = scrollbar ? Math.max(ww - t_x - t_margin - seekbar_w - 10, 0) : Math.max(ww - t_x - t_margin, 0);
    
    temp_bmp = gdi.CreateImage(1, 1);
    temp_gr = temp_bmp.GetGraphics();
    
    header_0 = lock_loading ? "l o c k" : "";
    h0_text_row_height = temp_gr.CalcTextHeight("Header_0", h0_font);
    var h0_text_array_tmp = header_0 ? temp_gr.EstimateLineWrap(header_0, h0_font, text_row_width).toArray() : []; 
    
    if (!history_show){
        header_1 = meta_artist ? meta_artist : ""; 
        var font = h1_font;
    } else {    
        header_1 = history_seach ? history_seach : "enter char (Back Space or ESC)";
        var font = t_font;
    }
    
    h1_char_width = temp_gr.CalcTextWidth(header_1.substr(0, 1), h1_font);
    
    h1_text_row_height = temp_gr.CalcTextHeight("Header_1", font);
    var h1_text_array_tmp = header_1 ? temp_gr.EstimateLineWrap(header_1, font, text_row_width).toArray() : [];

    var font = data_main == 0 ? t2_font : h2_font;
    h2_text_row_height = temp_gr.CalcTextHeight("Header_2", font);
    var h2_text_array_tmp = header_2 ? temp_gr.EstimateLineWrap(header_2, font, text_row_width).toArray() : [];
    
    text_row_height = temp_gr.CalcTextHeight("Biography", t_font);

    info_text_idx = data_main == 0 ? 0 : data_main + data_other_idx;
    info_text_show = window.GetProperty("info text " + info_text_idx);

    if (Math.abs(txt_x - old_txt_x) > 10 || refresh_txt){

        var info_text_arr_tmp = [];
        
        info_text_color_arr = [];
        info_text_font_arr = [];
        
        selected_item_rows_tmp = [];

        /////////////////////////////////////////////////////////////////////////
        
        if (!history_show && info_text_show && info_text_arr.length > 0){
            for (var i = 0; i < info_text_arr.length; i++) {
                var color;
                var font;
            
                if (info_text_color[i] == "h1_color") color = h1_color;
                if (info_text_color[i] == "t_color") color = t_color;
            
                if (info_text_font[i] == "t2_font") font = t2_font;
                if (info_text_font[i] == "t_font") font = t_font;

                var tmp_arr = temp_gr.EstimateLineWrap( info_text_arr[i], font, text_row_width).toArray();
                info_text_arr_tmp = info_text_arr_tmp.concat(tmp_arr);

                for (var j = 0; j < tmp_arr.length; j++) {
                    info_text_color_arr.push(color);
                    info_text_font_arr.push(font);
                    
                    if (j % 2){
                        if ( info_text_arr[i] == popular_this_week || info_text_arr[i] == latest_release){
                            selected_item_rows_tmp.push(info_text_arr[i]);//*
                        } else  {
                            selected_item_rows_tmp.push("");
                        }
                    }
                }
            }
            
            info_text_arr_tmp.push("\n", 0);
        }
        ///////////////////////////////////////////////////////////////////////////////////
        
        var history_arr_tmp = [];
        
        if (history_show && history_arr.length > 0){
            for (var i = 0; i < history_arr.length; i++) {

                var tmp_arr = temp_gr.EstimateLineWrap( history_arr[i], t_font, text_row_width).toArray();
                history_arr_tmp = history_arr_tmp.concat(tmp_arr);

                for (var j = 0; j < tmp_arr.length; j++) {
                    if (j % 2){
                        selected_item_rows_tmp.push(history_arr[i]);
                    }
                }
            }
            
            info_text_arr_tmp = history_arr_tmp;
        }

        var text_array_tmp = [];
        var t = no_img_msg + text;
        if (t) text_array_tmp = temp_gr.EstimateLineWrap(t, t_font, text_row_width).toArray();
        
        text_array = [];
        text_array = text_array.concat(info_text_arr_tmp, text_array_tmp);

        old_txt_x = txt_x;
        refresh_txt = false;
    }

    temp_bmp.ReleaseGraphics(temp_gr);
    temp_bmp.Dispose();
    temp_gr = null;
    temp_bmp = null;
    CollectGarbage();
    
    h0_y = Math.round(txt_y) + t_margin;
    h0_text_visable_area = Math.floor(Math.max(0, window.Height - t_margin - h0_y));
    h0_text_visable_rows = Math.max(1, Math.floor(h0_text_visable_area / h0_text_row_height));

    h0_text_array = [];
    for (var i = 0; i < h0_text_array_tmp.length; i += 2) {
        h0_text_array.push(trim(h0_text_array_tmp[i]));
    }
    
    h1_y = h0_y + h0_text_array.length * h0_text_row_height;
    h1_text_visable_area = Math.floor(Math.max(0, window.Height - t_margin - h1_y));
    h1_text_visable_rows = Math.max(1, Math.floor(h1_text_visable_area / h1_text_row_height));

    h1_text_array = [];
    for (var i = 0; i < h1_text_array_tmp.length; i += 2) {
        h1_text_array.push(trim(h1_text_array_tmp[i]));
    }

    h2_y = h1_y + h1_text_array.length * h1_text_row_height + 6;
    h2_text_visable_area = Math.floor(Math.max(0, window.Height - t_margin - h2_y));
    h2_text_visable_rows = Math.floor(h2_text_visable_area / h2_text_row_height);

    h2_text_array = [];
    for (var i = 0; i < h2_text_array_tmp.length; i += 2) {
        h2_text_array.push(trim(h2_text_array_tmp[i]));
    }
    
    t_y = (header_2.length > 0 ? h2_y + h2_text_array.length * h2_text_row_height : h1_y + h1_text_array.length * h1_text_row_height + 6) + text_row_height;
    text_visable_area = Math.floor(Math.max(0, window.Height - t_margin - t_y));
    text_visable_rows = Math.floor(text_visable_area / text_row_height);

    text_visable_height = text_visable_rows * text_row_height;
    text_rows = text_array.length / 2;
    
    text_height = text_rows * text_row_height;
    
    if (text_visable_height + scroll * -1 > text_height && scroll < 0) {
        scroll = scroll_ = 0;
    }

    seekbar_k = text_visable_height / text_rows;
    
    window.Repaint();
}

function strip_tags(t) {
    doc.open();
    var div = doc.createElement("div");
    div.innerHTML = t.replace(/<[Pp][^>]*>/g, "").replace(/<\/[Pp]>/g, "<br>").replace(/\n/g, "<br>");
    var text = div.innerText;
    doc.close();
    return text;
}

function save_txt_file(t, file){
    if (!t || !meta_artist) return; 

    path = artist_folder_path(clean(meta_artist));
    utils.WriteINI( path + "\\" + clean(meta_artist) + "_artist_info.ini", "meta_artist", "meta_artist", meta_artist);
    
    if (fso.FolderExists(artist_folder_path(clean(meta_artist)))){
        try {
            file = fso.OpenTextFile( file, 2, true, -1)
            file.Write(t);
            file.Close();
        } catch(e) {
            return;
        }
    }
}

var menu_items = [
    "Selected languages",
    "Selection mode",
    "last.fm",
    "External links",
    "Refresh",
    "History",
    "Search by",
    "Text",
    "Image",
    "Storage",
    "Language selection",
    "Help",
    "Properties",
    "Configure"
];

function main_menu_setting(x, y){
    for (var i = 0; i < menu_items.length; i++) {
        window.GetProperty("mi_" + menu_items[i], false);
    }
    
    var _menu = window.CreatePopupMenu();

    for (var i = 1; i < menu_items.length + 1; i++) {
        _menu.AppendMenuItem(MF_ENABLED, i, menu_items[i - 1]);   
        _menu.CheckMenuItem(i - 0, window.GetProperty("mi_" + menu_items[i - 1]));
    }
    
    _menu.AppendMenuItem(MF_SEPARATOR, 0, 0); 
    _menu.AppendMenuItem(MF_ENABLED, 100, "Return to main menu"); 

    ret = _menu.TrackPopupMenu(x, y);

    switch (true) {
    case (ret >= 1 && ret <= menu_items.length + 1):
        selected_item = window.GetProperty("mi_" + menu_items[ret - 1]);
        window.SetProperty("mi_" + menu_items[ret - 1], selected_item == false ? true : false);
        main_menu_setting(x, y);
        break;
    }
    
    switch (ret) {
    case 100:
        on_mouse_rbtn_up (x, y);
        break;
    }
    _menu.Dispose();
}

function mi_prop(item){
    return  window.GetProperty("mi_" + item) ? true : false;
}

function mi_dim(t1, t2) {
    w = 35;
    return (t1 + t2).length > w ? (t1 + t2).substr(0, w - 3) + "..." : t1 + t2; 
}

function on_mouse_rbtn_up (x, y){   
    var _menu = window.CreatePopupMenu();
    var _group_20 = window.CreatePopupMenu();
    
    function mi(item){
        return  window.GetProperty("mi_" + item) ? _menu : _group_20;
    }

    for (var i = 1; i < lang_arr.length + 1; i++) {
        menuItem = get_text_menu(lang_arr[i - 1]);
        mi("Selected languages").AppendMenuItem(MF_ENABLED, i, menuItem);  
        mi("Selected languages").CheckMenuRadioItem(i, lang_arr.length + 1, window.GetProperty("lang") + 1); 
        try { 
            mi("Selected languages").EnableMenuItem(window.GetProperty("lang") + 1, 1);
        } catch(e){};
    }
    
    mi("Selected languages").AppendMenuItem(MF_SEPARATOR, 0, 0); 

    var _group_selection_mode = window.CreatePopupMenu();
        _group_selection_mode.AppendTo(mi("Selection mode"), MF_ENABLED, "Selection mode");

        _group_selection_mode.AppendMenuItem(MF_ENABLED, 40, "Prefer now playing");   
        _group_selection_mode.AppendMenuItem(MF_ENABLED, 41, "Follow selected track");   
        _group_selection_mode.CheckMenuRadioItem(40, 41 , selection_mode + 40);
        try { 
            _group_selection_mode.EnableMenuItem(selection_mode + 40, 1);
        } catch(e){};
        
        mi("Selection mode").AppendMenuItem(MF_SEPARATOR, 0, 0); 

    MF_STRING = meta_artist ? MF_ENABLED : MF_GRAYED;
    var artist_txt = mi_dim("Artist : ", meta_artist);
    _menu.AppendMenuItem(MF_STRING, 50, artist_txt + (data_main == 1 ? " *" : "")); 
    _menu.CheckMenuRadioItem(50, 50 , data_main + 50);
    try { 
        _menu.EnableMenuItem(data_main + 50, 1);
    } catch(e){};
    
    _menu.AppendMenuItem(MF_STRING, 52, data_other[0][0] + (data_main == 0 && data_other_idx == 0 ? " *" : ""));   
    //_menu.AppendMenuItem(MF_STRING, 53, data_other[1][0] + (data_main == 0 && data_other_idx == 1 ? " *" : ""));   
    _menu.AppendMenuItem(MF_STRING, 54, data_other[2][0] + (data_main == 0 && data_other_idx == 2 ? " *" : "")); 
    
    MF_STRING = meta_album ?  MF_ENABLED : MF_GRAYED;
    var meta_album_txt = mi_dim(data_other[3][0], meta_album);
    _menu.AppendMenuItem(MF_STRING, 55, meta_album_txt + (data_main == 0 && data_other_idx == 3 ? " *" : ""));
    
    MF_STRING = meta_title ?  MF_ENABLED : MF_GRAYED;
    var meta_title_txt = mi_dim(data_other[4][0], meta_title);
    _menu.AppendMenuItem(MF_STRING, 56, meta_title_txt + (data_main == 0 && data_other_idx == 4 ? " *" : ""));
    
    var meta_title_txt = mi_dim(data_other[5][0], meta_title);
    _menu.AppendMenuItem(MF_STRING, 57, meta_title_txt + (data_main == 0 && data_other_idx == 5 ? " *" : ""));

    if (data_main == 1){
        _menu.CheckMenuRadioItem(52, 57 , data_other_idx + 52);
        try { 
            _menu.EnableMenuItem(data_other_idx + 52, 1);
        } catch(e){};            
    }

    _menu.AppendMenuItem(MF_SEPARATOR, 0, 0);

    /////////////////////////////////////////////////////////////////////////////////////////    

    switch(data_main) {	
    case 0:	
        lastFm_query_text = meta_artist ? meta_artist : "";
        lastFm_query = encodeURIComponent(meta_artist);
        break;	
    case 1:					
        switch(data_other_idx) {						
        case 0:	
        case 1:						
            lastFm_query_text = header_2 ? header_2 : "";
            lastFm_query = encodeURIComponent(meta_artist) + "/" + encodeURIComponent(header_2);
            break;						
        case 2:						
            lastFm_query_text = header_2 ? header_2 : "";
            lastFm_query = encodeURIComponent(header_2);
            break;	
        case 3:	
            lastFm_query_text = meta_album ? meta_album : "";
            lastFm_query = encodeURIComponent(meta_artist) + "/" + encodeURIComponent(meta_album);
            break;
        case 4:
        case 5:	
            lastFm_query_text = meta_title ? meta_title : "";
            lastFm_query = encodeURIComponent(meta_artist) + "/" + (meta_album ? encodeURIComponent(meta_album) + "/" : "_/") + encodeURIComponent(meta_title);
            break;
        }						
        break;						
    }	   

    MF_STRING = lastFm_query_text ? MF_ENABLED : MF_GRAYED;
    mi("last.fm").AppendMenuItem(MF_STRING, 60, mi_dim("last.fm : ", lastFm_query_text));

    var _group_external_links = window.CreatePopupMenu();
        MF_STRING = external_links.length > 0 ? MF_ENABLED : MF_GRAYED;
        
        _group_external_links.AppendTo(mi("External links"), MF_STRING, "External links ...");
    
        for (var i = 70; i < external_links.length + 70; i += 2) {
            var links_txt = mi_dim("", external_links[i - 70]);
            _group_external_links.AppendMenuItem(MF_ENABLED, i, links_txt); 
        }

/*
        var _group_Copy_to_folder_containing_track = window.CreatePopupMenu();
            MF_STRING = images.length > 0 ? MF_ENABLED : MF_GRAYED;
            _group_Copy_to_folder_containing_track.AppendTo(_group_10, MF_STRING, "Copy to folder containing track ...");
            
            _group_Copy_to_folder_containing_track.AppendMenuItem(MF_STRING, 80, "Copy file");
            _group_Copy_to_folder_containing_track.AppendMenuItem(MF_STRING, 81, "Copy files");

*/

    mi("Refresh").AppendMenuItem(MF_ENABLED, 100, "Refresh");
    mi("History").AppendMenuItem(MF_ENABLED, 110, "History");
    
    if(mi_prop("last.fm") || mi_prop("External links") || mi_prop("Refresh") || mi_prop("History")) _menu.AppendMenuItem(MF_SEPARATOR, 0, 0);
    if(!mi_prop("last.fm") || !mi_prop("External links") || !mi_prop("Refresh") || !mi_prop("History")) _group_20.AppendMenuItem(MF_SEPARATOR, 0, 0);

    /////////////////////////////////////////////////////////////////////////////////////////    

    var _group_search_by = window.CreatePopupMenu(); 
        _group_search_by.AppendTo(mi("Search by"), MF_ENABLED, "Search by : " + search_by[search_by_idx]);
            
        _group_search_by.AppendMenuItem(MF_ENABLED, 130, search_by[0]);
        _group_search_by.AppendMenuItem(MF_ENABLED, 131, search_by[1]);
        _group_search_by.AppendMenuItem(MF_ENABLED, 132, search_by[2]);
        _group_search_by.CheckMenuRadioItem(130, 132, search_by_idx + 130);
        try { 
            _group_search_by.EnableMenuItem(search_by_idx + 130, 1);
        } catch(e){}; 

    var _group_text = window.CreatePopupMenu();
        _group_text.AppendTo(mi("Text"), MF_ENABLED, "Text");
        
        var _group_text_alignment = window.CreatePopupMenu();
            _group_text_alignment.AppendTo(_group_text, MF_ENABLED, "Text alignment");
        
            var _group_text_alignment_h1 = window.CreatePopupMenu();
                _group_text_alignment_h1.AppendTo(_group_text_alignment, MF_ENABLED, "Header 1 : " + text_alignment[text_alignment_h1][0]);
                
                _group_text_alignment_h1.AppendMenuItem(MF_ENABLED, 140, text_alignment[0][0]);
                _group_text_alignment_h1.AppendMenuItem(MF_ENABLED, 141, text_alignment[1][0]);
                _group_text_alignment_h1.AppendMenuItem(MF_ENABLED, 142, text_alignment[2][0]);
                _group_text_alignment_h1.CheckMenuRadioItem(140, 142, text_alignment_h1 + 140); 
                try { 
                    _group_text_alignment_h1.EnableMenuItem(text_alignment_h1 + 140, 1);
                } catch(e){}; 

            var _group_text_alignment_h2 = window.CreatePopupMenu();
                _group_text_alignment_h2.AppendTo(_group_text_alignment, MF_ENABLED, "Header 2 : " + text_alignment[text_alignment_h2][0]);
                
                _group_text_alignment_h2.AppendMenuItem(MF_ENABLED, 150, text_alignment[0][0]);
                _group_text_alignment_h2.AppendMenuItem(MF_ENABLED, 151, text_alignment[1][0]);
                _group_text_alignment_h2.AppendMenuItem(MF_ENABLED, 152, text_alignment[2][0]);
                _group_text_alignment_h2.CheckMenuRadioItem(150, 152, text_alignment_h2 + 150);
                try { 
                    _group_text_alignment_h2.EnableMenuItem(text_alignment_h2 + 150, 1);
                } catch(e){};  

            var _group_text_alignment_t = window.CreatePopupMenu();
                _group_text_alignment_t.AppendTo(_group_text_alignment, MF_ENABLED, "Main text : " + text_alignment[text_alignment_t][0]);
                
                _group_text_alignment_t.AppendMenuItem(MF_ENABLED, 160, text_alignment[0][0]);
                _group_text_alignment_t.AppendMenuItem(MF_ENABLED, 161, text_alignment[1][0]);
                _group_text_alignment_t.AppendMenuItem(MF_ENABLED, 162, text_alignment[2][0]);
                _group_text_alignment_t.CheckMenuRadioItem(160, 162, text_alignment_t + 160); 
                
                try { 
                    _group_text_alignment_t.EnableMenuItem(text_alignment_t + 160, 1);
                } catch(e){}; 

        var _group_font_style = window.CreatePopupMenu();
            _group_font_style.AppendTo(_group_text, MF_ENABLED, "Font style");//
        
            var _group_font_style_h1 = window.CreatePopupMenu();
                _group_font_style_h1.AppendTo(_group_font_style, MF_ENABLED, "Header 1 : " + font_style[font_style_h1][0]);
                
                _group_font_style_h1.AppendMenuItem(MF_ENABLED, 170, font_style[0][0]);
                _group_font_style_h1.AppendMenuItem(MF_ENABLED, 171, font_style[1][0]);
                _group_font_style_h1.AppendMenuItem(MF_ENABLED, 172, font_style[2][0]);
                _group_font_style_h1.AppendMenuItem(MF_ENABLED, 173, font_style[3][0]);
                _group_font_style_h1.CheckMenuRadioItem(170, 173, font_style_h1 + 170); 
                try { 
                    _group_font_style_h1.EnableMenuItem(font_style_h1 + 170, 1);
                } catch(e){}; 

            var _group_font_style_h2 = window.CreatePopupMenu();
                _group_font_style_h2.AppendTo(_group_font_style, MF_ENABLED, "Header 2 : " + font_style[font_style_h2][0]);
                
                _group_font_style_h2.AppendMenuItem(MF_ENABLED, 180, font_style[0][0]);
                _group_font_style_h2.AppendMenuItem(MF_ENABLED, 181, font_style[1][0]);
                _group_font_style_h2.AppendMenuItem(MF_ENABLED, 182, font_style[2][0]);
                _group_font_style_h2.AppendMenuItem(MF_ENABLED, 183, font_style[3][0]);
                _group_font_style_h2.CheckMenuRadioItem(180, 183, font_style_h2 + 180); 
                try { 
                    _group_font_style_h2.EnableMenuItem(font_style_h2 + 180, 1);
                } catch(e){}; 

            var _group_font_style_t = window.CreatePopupMenu();
                _group_font_style_t.AppendTo(_group_font_style, MF_ENABLED, "Main text : " + font_style[font_style_t][0]);
                
                _group_font_style_t.AppendMenuItem(MF_ENABLED, 190, font_style[0][0]);
                _group_font_style_t.AppendMenuItem(MF_ENABLED, 191, font_style[1][0]);
                _group_font_style_t.AppendMenuItem(MF_ENABLED, 192, font_style[2][0]);
                _group_font_style_t.AppendMenuItem(MF_ENABLED, 193, font_style[3][0]);
                _group_font_style_t.CheckMenuRadioItem(190, 193, font_style_t + 190); 
                try { 
                    _group_font_style_t.EnableMenuItem(font_style_t + 190, 1);
                } catch(e){}; 

        _group_text.AppendMenuItem(MF_ENABLED, 200, "Text shadow");
        _group_text.CheckMenuItem(200, text_shadow);
        
        _group_text.AppendMenuItem(MF_ENABLED, 210, "Show scrollbar");
        _group_text.CheckMenuItem(210, scrollbar);
 
    /////////////////////////////////////////////////////////////////////////////////////////    

    var _group_image = window.CreatePopupMenu();
        _group_image.AppendTo(mi("Image"), MF_ENABLED, "Image");
        
        _group_image.AppendMenuItem(MF_ENABLED, 220, "Show Image");
        _group_image.CheckMenuItem(220, img_show);
        
        _group_image.AppendMenuItem(MF_SEPARATOR, 0, 0); 
        
        var _group_image_alignment = window.CreatePopupMenu();
            _group_image_alignment.AppendTo(_group_image, MF_ENABLED, "Image alignment"); 

            _group_image_alignment.AppendMenuItem(MF_ENABLED, 230, img_alignment[0]);
            _group_image_alignment.AppendMenuItem(MF_ENABLED, 231, img_alignment[1]);
            _group_image_alignment.AppendMenuItem(MF_ENABLED, 232, img_alignment[2]);
            _group_image_alignment.AppendMenuItem(MF_ENABLED, 233, img_alignment[3]);
            _group_image_alignment.AppendMenuItem(MF_ENABLED, 234, img_alignment[4]);
            _group_image_alignment.AppendMenuItem(MF_ENABLED, 235, img_alignment[5]);
            _group_image_alignment.CheckMenuRadioItem(230, 235, img_alignment_idx + 230);
            try { 
                _group_image_alignment.EnableMenuItem(img_alignment_idx + 230, 1);
            } catch(e){};

        var _group_download_quality = window.CreatePopupMenu();
            _group_download_quality.AppendTo(_group_image, MF_ENABLED, "Download quality : " + quality[quality_idx][0]);
            
            _group_download_quality.AppendMenuItem(MF_ENABLED, 240, quality[0][0]);
            _group_download_quality.AppendMenuItem(MF_ENABLED, 241, quality[1][0]);
            _group_download_quality.AppendMenuItem(MF_ENABLED, 242, quality[2][0]);
            _group_download_quality.CheckMenuRadioItem(240, 242, quality_idx + 240);
            try { 
                _group_download_quality.EnableMenuItem(quality_idx + 240, 1);
            } catch(e){};

        MF_STRING = images[img_selected] ? MF_ENABLED : MF_GRAYED;
        _group_image.AppendMenuItem(MF_STRING, 250, "Open image");
        
        var _group_default_img = window.CreatePopupMenu();
            _group_default_img.AppendTo(_group_image, MF_ENABLED, "Default image"); 

            _group_default_img.AppendMenuItem(MF_ENABLED, 260, "Default image"); // 250
            _group_default_img.CheckMenuItem(260, default_img);
        
            var _group_lastFm_logo = window.CreatePopupMenu();
                MF_STRING = !default_img ? MF_ENABLED : MF_GRAYED;
                _group_lastFm_logo.AppendTo(_group_default_img, MF_STRING, "last.fm logo image");

                _group_lastFm_logo.AppendMenuItem(MF_ENABLED, 270, "1");   
                _group_lastFm_logo.AppendMenuItem(MF_ENABLED, 271, "2");   
                _group_lastFm_logo.AppendMenuItem(MF_ENABLED, 272, "3");  
                _group_lastFm_logo.AppendMenuItem(MF_ENABLED, 273, "4");    
                _group_lastFm_logo.AppendMenuItem(MF_ENABLED, 274, "5");  
                _group_lastFm_logo.CheckMenuRadioItem(270, 274 , logo_img_idx - 0 + 270);
                try { 
                    _group_lastFm_logo.EnableMenuItem(logo_img_idx + 270, 1);
                } catch(e){};

        _group_image.AppendMenuItem(MF_ENABLED, 280, "Border");
        _group_image.CheckMenuItem(280, img_border);

        _group_image.AppendMenuItem(MF_ENABLED, 290, "Fade effect");
        _group_image.CheckMenuItem(290, fade_effect);
        
        _group_image.AppendMenuItem(MF_ENABLED, 300, "Image download limit (" + limit + ")");
        
        if(mi_prop("Search by") || mi_prop("Text") || mi_prop("Image")) _menu.AppendMenuItem(MF_SEPARATOR, 0, 0);
        if(!mi_prop("Search by") || !mi_prop("Text") || !mi_prop("Image")) _group_20.AppendMenuItem(MF_SEPARATOR, 0, 0);
        
    /////////////////////////////////////////////////////////////////////////////////////////    

    var _group_storage = window.CreatePopupMenu();
        _group_storage.AppendTo(mi("Storage"), MF_ENABLED, "Storage");
        
        _group_storage.AppendMenuItem(MF_ENABLED, 310, "Save images and text");
        _group_storage.CheckMenuItem(310, save_images);

        _group_storage.AppendMenuItem(MF_ENABLED, 320, save_images ? "Use artist folder to save" : "Use artist folder for temporary storage");  
        _group_storage.CheckMenuItem(320, save_images_to_artist_folder); 
        
        _group_storage.AppendMenuItem(MF_SEPARATOR, 0, 0); 
        _group_storage.AppendMenuItem(MF_ENABLED, 330, "Delete temporary internet files");
        
        mi("Storage").AppendMenuItem(MF_SEPARATOR, 0, 0); 
 
    var _group_language_selection = window.CreatePopupMenu();
        _group_language_selection.AppendTo(mi("Language selection"), MF_ENABLED, "Language selection");
    
        for (var i = 20; i < language_text.length + 20; i++) {
            menuItem = language_text[i - 20][1];
            _group_language_selection.AppendMenuItem(MF_ENABLED, i, menuItem);   
            _group_language_selection.CheckMenuItem(i, window.GetProperty(language_text[i - 20][0]));
        }
        mi("Language selection").AppendMenuItem(MF_SEPARATOR, 0, 0); 

    mi("Help").AppendMenuItem(MF_ENABLED, 600, "Help ...");
    mi("Help").AppendMenuItem(MF_SEPARATOR, 0, 0);
    
    mi("Properties").AppendMenuItem(MF_ENABLED, 610, "Properties");
    mi("Configure").AppendMenuItem(MF_ENABLED, 620, "Configure ...");
    
    if (mi_prop("Properties") || mi_prop("Configure")) _menu.AppendMenuItem(MF_SEPARATOR, 0, 0);
    if (!mi_prop("Properties") || !mi_prop("Configure")) _group_20.AppendMenuItem(MF_SEPARATOR, 0, 0);
    
    _group_20.AppendMenuItem(MF_ENABLED, 500, "Main menu setting"); // main menu configuration

    _group_20.AppendTo(_menu, MF_ENABLED, "More ..."); // management and settings

    //_menu.AppendMenuItem(MF_ENABLED, 1000, "");
    //_menu.CheckMenuItem(1000, "");

    //_menu.AppendMenuItem(MF_ENABLED, 2000, "");
    //_menu.CheckMenuItem(2000, "");

    /////////////////////////////////////////////////////////////////////////////////////////    
    
    ret = _menu.TrackPopupMenu(x + 20, y);
    
    switch (true) {
        case (ret >= 1 && ret < lang_arr.length + 1):
        lang_idx = ret - 1;
        window.SetProperty("lang", lang_idx);
        path = artist_folder_path(clean(meta_artist));
        get_text(path, meta_artist, meta_album, meta_title);
        break;
    }
    
    switch (true) {
        case (ret >= 20 && ret < language_text.length + 20):
        tmp_lang_idx = lang_arr[lang_idx];
        var tmp = window.GetProperty(language_text[ret - 20][0]);
        window.SetProperty(language_text[ret - 20][0], !tmp);
        create_lang_arr();
        path = artist_folder_path(clean(meta_artist));
        get_text(path, meta_artist, meta_album, meta_title);
        on_mouse_rbtn_up (x, y);
        break;
    }
    
    switch (true) {
        case (ret >= 70 && ret < external_links.length + 70):
        external_links_query = external_links[ret - 70 + 1];
        try {    
            WshShell.run(external_links_query);
        } catch (e) {};          
        break;
    }

    switch (ret) {
    case 40:
    case 41:
        old_album = "";
        old_title = "";
        selection_mode = ret - 40;
        window.SetProperty("selection mode", selection_mode);
        on_item_focus_change();
        break;
    case 50:
    case 51:
        data_main = ret - 50;
        window.SetProperty("data_main: bio or album, similar", data_main); 
            if (history_show && lock_loading){
                history_show = false;
                lock_loading = false;
            }
        get_img(meta_artist, meta_album, meta_title);
        break;
    case 52:
    case 53:
    case 54:
    case 55:
    case 56:
    case 57:
        data_other_idx = ret - 52;
        window.SetProperty("data_other_idx", data_other_idx);
            if (history_show && lock_loading){
                history_show = false;
                lock_loading = false;
            }
        if (data_main == 0) {
            data_main = 1;
            window.SetProperty("data_main: bio or album, similar", data_main); 
        }
        get_img(meta_artist, meta_album, meta_title);
        break;
    case 60:
        try {    
            WshShell.run("https://www.last.fm/" + lang_query(lang_idx) + "music/" + lastFm_query);
        } catch (e) {};
        break;
    case 80:
        copy_files(0);
        break;
    case 81:
        copy_files(1);
        break;
    case 90: 
        // not use
        break; 
    case 100:
        refresh_data = true;
        on_metadb_changed();
        break;
    case 110:
        // "History"
        history_show = true;
        lock_loading = true; 
        lock_mode();
        history_seach = "";
        get_history();
        break;
    case 120:
        // not use
        break;        
    case 130:
    case 131:
    case 132:
        search_by_idx = ret - 130;
        window.SetProperty("search by idx", search_by_idx);
        on_item_focus_change();
        on_mouse_rbtn_up (x, y);
        break;
    case 140:
    case 141:
    case 142:
        text_alignment_h1 = ret - 140;
        window.SetProperty("text alignment : header 1", text_alignment_h1);
        window.Repaint();
        on_mouse_rbtn_up (x, y);
        break;  
    case 150:
    case 151:
    case 152:
        text_alignment_h2 = ret - 150;
        window.SetProperty("text alignment : header 2", text_alignment_h2);
        window.Repaint();	
        on_mouse_rbtn_up (x, y);
        break;  
    case 160:
    case 161:
    case 162:
        text_alignment_t = ret - 160;
        window.SetProperty("text alignment : text", text_alignment_t);
        window.Repaint();
        on_mouse_rbtn_up (x, y);
        break; 
    case 170:
    case 171:
    case 172:
    case 173:
        font_style_h1 = ret - 170;
        window.SetProperty("text: font style: header 1", font_style_h1);
        get_font();
        refresh_txt = true;
        get_text_array();
        on_mouse_rbtn_up (x, y);
        break; 
    case 180:
    case 181:
    case 182:
    case 183:
        font_style_h2 = ret - 180;
        window.SetProperty("text: font style: header 2", font_style_h2);
        get_font();
        refresh_txt = true;
        get_text_array();
        on_mouse_rbtn_up (x, y);
        break; 
    case 190:
    case 191:
    case 192:
    case 193:
        font_style_t = ret - 190;
        window.SetProperty("text: font style: text", font_style_t);
        get_font();
        refresh_txt = true;
        get_text_array();
        on_mouse_rbtn_up (x, y);
        break; 
    case 200:
        text_shadow = !text_shadow;
        window.SetProperty("text: shadow", text_shadow);
        window.Repaint();
        //on_mouse_rbtn_up (x, y);
        break; 
    case 210:
        scrollbar = !scrollbar;
        window.SetProperty("scrollbar", scrollbar);
        refresh_txt = true;
        get_text_array();
        //on_mouse_rbtn_up (x, y);
        break; 
    case 220:
        img_show = !img_show;
        window.SetProperty("img off", img_show);
        default_fader_ini();
        images[img_selected] && next_image(img_selected);
        break;
    case 230:
    case 231:
    case 232: 
    case 233:
    case 234:
    case 235:
        img_alignment_idx = ret - 230;
        window.SetProperty("align mode", img_alignment_idx);
        img_size_recount = false;
        def_img_size_recount = false;
        window.Repaint();
        //on_mouse_rbtn_up (x, y);
        break;
    case 240:
    case 241:
    case 242:    
        quality_idx = ret - 240;
        window.SetProperty("download quality", quality_idx);
        refresh_data = true;
        on_metadb_changed();
        //on_mouse_rbtn_up (x, y);
        break;
    case 250:
        try {
            if (images[img_selected]) WshShell.run( '"' + img_file_names[img_selected] + '"' );					
        } catch(e) {};
        break; 
    case 260:
        default_img = !default_img;
        window.SetProperty("default img", default_img);
        default_img_set = true;
        fdelay2();
        //on_mouse_rbtn_up (x, y);
        break;        
    case 270:
    case 271:
    case 272: 
    case 273:
    case 274:
        logo_img_idx = ret - 270;
        window.SetProperty("logo_img_idx", logo_img_idx);
        logo_img = null;
        logo_img_set = true;
        fdelay2();
        //on_mouse_rbtn_up (x, y);
        break;
    case 280:
        img_border = !img_border;
        window.SetProperty("img border", img_border);
        img_size_recount = false;
        def_img_size_recount = false;
        window.Repaint();
        //on_mouse_rbtn_up (x, y);
        break;
    case 290:
        fade_effect = !fade_effect;
        window.SetProperty("fade effect", fade_effect);
        default_fader_ini();
        break; 
    case 300:
        download_limit(x, y);
        break;
    case 310:
        save_images = !save_images;
        window.SetProperty("save images", save_images);
        break;
    case 320:
        save_images_to_artist_folder = !save_images_to_artist_folder;
        window.SetProperty("save to artist folder containing track", save_images_to_artist_folder);
        break       
    case 330:
        try {
            WshShell.Run("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8");
            //WshShell.Run("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2");
        } catch (e) {};
        break; 


    case 1000:
        break;
    case 2000:
        break;


    case 500:
        main_menu_setting(x, y);
        break;
    case 600:
        help();
        break;
    case 610:
        window.ShowProperties();
        break;   
    case 620:
        window.ShowConfigure();   
        break;
    }
    _menu.Dispose(); 
    _group_20.Dispose(); 
    _group_selection_mode.Dispose();
    _group_external_links.Dispose();
    _group_search_by.Dispose(); 	
    _group_text.Dispose();
    _group_text_alignment.Dispose();
    _group_text_alignment_h1.Dispose();
    _group_text_alignment_h2.Dispose();
    _group_text_alignment_t.Dispose();
    _group_font_style.Dispose();
    _group_font_style_h1.Dispose();
    _group_font_style_h2.Dispose();
    _group_font_style_t.Dispose();
    _group_image.Dispose();
    _group_image_alignment.Dispose();
    _group_download_quality.Dispose();
    _group_default_img.Dispose();
    _group_lastFm_logo.Dispose(); 
    _group_storage.Dispose(); 
    _group_language_selection.Dispose(); 
    return true;   				
} 

function download_limit(x, y){
    var _menu = window.CreatePopupMenu();

    _menu.AppendMenuItem(MF_ENABLED, 1, "Increase"); 
    _menu.AppendMenuItem(MF_ENABLED, 2, "Download limit " + limit); 
    _menu.AppendMenuItem(MF_ENABLED, 3, "Decrease"); 

    ret = _menu.TrackPopupMenu(x, y);

    switch (ret) {
    case 1:
        limit = limit + 1;
        window.SetProperty("img download limit", limit);
        download_limit(x, y);
        break;
    case 2:
        on_mouse_rbtn_up (x, y);
        break;
    case 3:
        limit = limit <= 1 ? 1 : limit - 1;
        window.SetProperty("img download limit", limit);
        download_limit(x, y);
        break;
    }
    _menu.Dispose();
}
	
function get_files_if_loaded(path, t_artist, t_album, t_title){	
    utils.WriteINI( path + "\\" + clean(meta_artist) + "_artist_info.ini", "meta_artist", "meta_artist", meta_artist);
    
    var i = 0;
    get_files_timer && window.ClearInterval(get_files_timer); 
    get_files_timer = window.SetInterval(function() {	
        i++;
        get_img_from_dir(path, t_artist, t_album, t_title);
        if (images.length > 0 || i >= 20) {
            next_image(0);
            get_text(path, t_artist, t_album, t_title);
            window.ClearInterval(get_files_timer); 
        }                 				
    }, 500);
}

function image_upload_delay(p, t_artist, t_album, t_title) {
    var upload_delay = window.SetTimeout(function() { 
        get_files_if_loaded(p, t_artist, t_album, t_title);
        window.ClearTimeout(upload_delay);
    }, upload_delay_time); 
}

function cycle_set_timer(){
        cycle_timer && window.ClearInterval(cycle_timer);
        cycle_timer = window.SetInterval(function() {
        cycle_step =  cycle_set ? 0 : cycle_step + 1;
        if (cycle > 0 && cycle_step >= cycle){
            if (images.length < limit) get_img_from_dir(artist_folder_path(clean(meta_artist)), meta_artist);			
            if (images.length > 1){			
                next_image(1);
                
                if (data_main != 0 && (data_other_idx == 0 || data_other_idx == 1  || data_other_idx == 2)){
                    path = artist_folder_path(clean(meta_artist));
                    get_text(path, meta_artist, meta_album, meta_title);
                }
                cycle_step = 0;			
            }			
        }
    }, 1000);			
}			
			
function fdelay(){			
    var delay_timer = window.SetTimeout(function() {			
        delay = false;		
        window.ClearTimeout(delay_timer);			
    }, 200);
}

function fdelay2(){	
    g_img = null;
    window.Repaint();
    default_fader_ini();
    default_img_set && default_img_ini();
    logo_img_set && logo_img_ini();

    var delay_timer = window.SetTimeout(function() {			
        images[img_selected] && next_image(img_selected);
        logo_img_set = false;
        default_img_set = false;
        window.ClearTimeout(delay_timer);	
        window.Repaint();		
    }, 1500);
}

function fader_timer(){
        img_size = calc_img_size(g_img);
        ftimer && window.ClearInterval(ftimer);
        ftimer = window.SetInterval(function() {
        fader = fader * 2;
        window.RepaintRect(img_size.x - img_border_width, img_size.y - img_border_width, img_size.width + img_border_width * 2, img_size.height + img_border_width * 2);      
        fader = fader == 0 ? 1 : fader;
        if (fader >= 255) {
            fader = 255;
            window.ClearInterval(ftimer);
        }
    }, 50);
}

function fader_timer_logo_on(){
        ftimer_logo && window.ClearInterval(ftimer_logo);
        ftimer_logo = window.SetInterval(function() {
        fader_logo = fade_effect ? Math.round(fader_logo + logo_img_transparence / 10) : 0;
        window.Repaint();
        if (fader_logo >= logo_img_transparence) {
            fader_logo = logo_img_transparence;
            window.ClearInterval(ftimer_logo);
        }
    }, 50);
}

function fader_timer_def_img_on(){
        def_img_size = calc_img_size(def_img);
        ftimer_def_img && window.ClearInterval(ftimer_def_img);
        ftimer_def_img = window.SetInterval(function() {
        fader_def_img = fade_effect ? Math.round(fader_def_img + default_img_transparence / 10) : 0;
        window.RepaintRect(def_img_size.x - img_border_width, def_img_size.y - img_border_width, def_img_size.width + img_border_width * 2, def_img_size.height + img_border_width * 2);  
        if (fader_def_img >= default_img_transparence) {
            fader_def_img = default_img_transparence;
            window.ClearInterval(ftimer_def_img);
        }
    }, 50);
}

function info_tooltip() {
    tooltip_on = true;
    tooltip_timer &&  window.ClearTimeout(tooltip_timer);
    tooltip_timer = window.SetTimeout(function() {
        tooltip_on = false;
        window.Repaint();
        tooltip_timer && window.ClearTimeout(tooltip_timer);
    },  tooltip_delay);
}

function load_last_fm_logo(){
    if(!fso.FileExists(script_path + "last_fm_ico.ico")) {
        var url = "http://static-web.last.fm/static/images/favicon.702b239b6194.ico"
        var file = "\"" + script_path + "last_fm_ico.ico" + "\"";
        WshShell.Run(vbs + " " + url + " " + file, false);
    }
    if(!fso.FileExists(script_path + "footer_logo.png")) {
        var url = "https://static-web.last.fm/static/images/footer_logo.ddcfd65712a6.png"
        var file = "\"" + script_path + "footer_logo.png" + "\"";
        WshShell.Run(vbs + " " + url + " " + file, false);
    }
    if(!fso.FileExists(script_path + "logo_static.png")) {
        var url = "https://www.last.fm/static/images/logo_static.png?7b581436b23f"
        var file = "\"" + script_path + "logo_static.png" + "\"";
        WshShell.Run(vbs + " " + url + " " + file, false);
    }
    if(!fso.FileExists(script_path + "logo_sq_256_new_large.png")) {
        var url = "https://d2r1vs3d9006ap.cloudfront.net/public/uploaded_images/10596530/logo_sq_256_new_large.png"
        var file = "\"" + script_path + "logo_sq_256_new_large.png" + "\"";
        WshShell.Run(vbs + " " + url + " " + file, false);
    }
    if(!fso.FileExists(script_path + "logo_sq_256_new_small.png")) {
        var url = "https://d2r1vs3d9006ap.cloudfront.net/public/uploaded_images/10596530/logo_sq_256_new_small.png"
        var file = "\"" + script_path + "logo_sq_256_new_small.png" + "\"";
        WshShell.Run(vbs + " " + url + " " + file, false);
    }
    if(!fso.FileExists(script_path + "logo.png")) {
        var url = "http://cdn.shopify.com/s/files/1/0270/7261/t/3/assets/logo.png?13435600546523064478" // ?????????????
        var file = "\"" + script_path + "logo.png" + "\"";
        WshShell.Run(vbs + " " + url + " " + file, false);
    }
    if(!fso.FileExists(script_path + "logo 2.png")) {
        var url = "http://cdn.shopify.com/s/files/1/0270/7261/t/1/assets/logo.png?13435600546523064478" // ?????????????
        var file = "\"" + script_path + "logo 2.png" + "\"";
        WshShell.Run(vbs + " " + url + " " + file, false);
    }
}

function create_download_file() {
    try {
        file = fso.CreateTextFile(script_path + "download.vbs" );
       
        var text =   
            "If (WScript.Arguments.Count <> 2) Then" + "\n\r" +   
            "   WScript.Quit" + "\n\r" +
            "End If" + "\n\r" + "\n\r" +   

            "url = WScript.Arguments(0)" + "\n\r" +   
            "file = WScript.Arguments(1)" + "\n\r"  + "\n\r" +   

            "Set objFSO = Createobject(" + '"Scripting.FileSystemObject"' + ")" + "\n\r" +   
            "If objFSO.Fileexists(file) Then" + "\n\r" +   
            "   Set objFSO = Nothing" + "\n\r" +
            "   WScript.Quit" + "\n\r" +
            "End If" + "\n\r" + "\n\r" +   

            "Set objXMLHTTP = CreateObject(" + '"MSXML2.XMLHTTP"' + ")" + "\n\r" +   
            "objXMLHTTP.open " + '"GET"' + ", url,false" + "\n\r" +   
            "objXMLHTTP.send()" + "\n\r" + "\n\r" +   

            "If objXMLHTTP.Status = 200 Then" + "\n\r" +   
            "   Set objADOStream = CreateObject(" + '"ADODB.Stream"' + ")" + "\n\r" +
            "   objADOStream.Open" + "\n\r" +
            "   objADOStream.Type = 1" + "\n\r" +
            "   objADOStream.Write objXMLHTTP.ResponseBody" + "\n\r" +
            "   objADOStream.Position = 0" + "\n\r" +
            "   objADOStream.SaveToFile file" + "\n\r" +
            "   objADOStream.Close" + "\n\r" +
            "   Set objADOStream = Nothing" + "\n\r" +
            "End If" + "\n\r" + "\n\r" +   

            "Set objFSO = Nothing" + "\n\r" +   
            "Set objXMLHTTP = Nothing"   
        ;

        file.WriteLine(text);
        file.Close();
    } catch(e) {};
}

function on_mouse_move(x, y) {
    window.SetCursor(IDC_HAND);
    
    //pos_x = x;
    pos_y = y; 
    
    on_header_0 = x >= txt_x && x < ww && y >= txt_y && y < h0_y + h0_text_row_height * h0_text_array.length ? true : false;
    on_header_1 = x >= txt_x && x < ww && y >= h1_y && y < h1_y + h1_text_row_height * h1_text_array.length + 6 ? true : false;
    on_header_2 = x >= txt_x && x < ww && y >= h2_y && y < h2_y + h2_text_row_height * h2_text_array.length ? true : false;
    on_info_text_btn = x >= txt_x && x < ww && y >= t_y - text_row_height && y < t_y ? true : false;
    on_text = x >= txt_x && x < seekbar_x && y >= t_y && y <= wh ? true : false;
    on_scrollbar = x >= seekbar_x && x < ww && y >= t_y && y <= wh ? true : false;
    on_seekbar = x >= seekbar_x && x < ww && y >= seekbar_y && y <= seekbar_y + seekbar_h ? true : false;
    on_img = !on_header_0 && !on_header_1 && !on_header_2 && !on_text && !on_info_text_btn && !on_scrollbar ? true : false;

    if (on_text_down){
        txt_x = x - delta_x;
        txt_y = y - delta_y;

        txt_x = Math.round(Math.max(0, Math.min(txt_x, ww - t_margin * 2 - h1_char_width - (scrollbar ? seekbar_w + 10 : 0))));
        txt_y = Math.round(Math.max(0, Math.min(txt_y, wh - (h1_text_row_height + t_margin * 2))));

        get_text_array();
    }
    
    if (on_seekbar_down){
        seekbar_posy = y + delta_y;
        scroll = y + delta_y >= 0 ? y + delta_y <= (text_rows - text_visable_rows) * seekbar_k ? Math.round(seekbar_posy / seekbar_k) : text_rows - text_visable_rows : 0;
        scroll = scroll * - 1 * text_row_height; 
        scroll_check();	
    }

    if (scrollbar && seekbar_x && seekbar_y && seekbar_h && !on_text_down){
        window.RepaintRect(seekbar_x, t_y, ww, wh);	
    }

    if (!on_text_down){ // info_text_btn
        window.RepaintRect(txt_x, t_y - text_row_height, ww, text_row_height);
    }
    
    if (lock_loading){ // lock_btn
        window.RepaintRect(t_x, txt_y, ww, h0_y + h0_text_row_height * h0_text_array.length);
    }

    if (on_header_1 && on_text_down) {							
        text_hiden = false;							
        window.SetProperty("txt hiden", text_hiden);							
    }							
							
    //if (tooltip_on) window.Repaint();	
    
    text_idx = Math.round(Math.floor((y - t_y) / text_row_height) + (scroll * -1 / text_row_height));
    text_idx = text_idx < scroll * -1 / text_row_height ? scroll * -1 / text_row_height : text_idx;
    text_idx = text_idx > (scroll * -1 / text_row_height) + text_visable_rows -1 ? (scroll * -1 / text_row_height + text_visable_rows) - 1 : text_idx;
    
    selected_item = selected_item_rows_tmp[text_idx];
    selected_item_rows = [];

    for (var j = 0; j < selected_item_rows_tmp.length; j++) {
        if (selected_item_rows_tmp[j]) {
            
            if (t_y + (j * text_row_height) - (scroll * -1) > 0){
                window.RepaintRect(t_x, t_y + (j * text_row_height) - (scroll * -1), text_row_width, text_row_height);
            }
            
            if (selected_item_rows_tmp[j] == selected_item) {
                selected_item_rows.push(j);
            } 
        } 
    }

    //////////////////////////////////////////////////////////////////////////////////////////////
    ///window.Repaint();	
    //////////////////////////////////////////////////////////////////////////////////////////////
}
	
function on_mouse_wheel(delta) {							
    ShiftDown = utils.IsKeyPressed(VK_SHIFT) ? true : false;							
    ControltDown = utils.IsKeyPressed(VK_CONTROL) ? true : false;							

    if (on_img && !cycle_set && !delay && !history_show){	
        if (images.length < limit) get_img_from_dir(artist_folder_path(clean(meta_artist)), meta_artist);	 
        if (img_file_names.length > 1){							
            delay = true;							
            fdelay();							
            next_image(delta);
            
            if (data_main != 0 && (data_other_idx == 0 || data_other_idx == 1 || data_other_idx == 2)){
                path = artist_folder_path(clean(meta_artist));
                get_text(path, meta_artist, meta_album, meta_title);
            }

            if (cycle > 0) cycle_step = 0;							
        }							
    }							

    if ((on_header_0 || on_header_1 || on_header_2 || on_text || on_info_text_btn || on_seekbar || on_scrollbar) && !ShiftDown && !ControltDown){	
        if (text_height > text_visable_height){
            wheel_id += delta;
            scroll -= (wheel_id * -1) * text_row_height * (on_seekbar || on_scrollbar ? text_visable_rows : 1); 
            scroll_check();	
        }
    }
   							
    if ((on_header_0 || on_header_1 || on_header_2 || on_text) && ShiftDown && !delay && !ControltDown){
        tooltip_t = "";
        delay = true;							
        fdelay();							

        if (on_header_0 && delta < 0) {font_size_h0 = Math.max(min_font_size, font_size_h0 -= 1)};							
        if (on_header_0 && delta > 0) {font_size_h0 = Math.min(max_font_size, font_size_h0 += 1)};							
        window.SetProperty("text: font size: header 0", font_size_h0);
        if (on_header_1 && delta < 0) {font_size_h1 = Math.max(min_font_size, font_size_h1 -= 1)};							
        if (on_header_1 && delta > 0) {font_size_h1 = Math.min(max_font_size, font_size_h1 += 1)};							
        window.SetProperty("text: font size: header 1", font_size_h1);
        if (data_main == 1 && on_header_2 && delta < 0) {font_size_h2 = Math.max(min_font_size, font_size_h2 -= 1)};							
        if (data_main == 1 && on_header_2 && delta > 0) {font_size_h2 = Math.min(max_font_size, font_size_h2 += 1)};							
        window.SetProperty("text: font size: header 2", font_size_h2);
        if (on_text && delta < 0) {font_size_t = Math.max(min_font_size, font_size_t -= 1)};							
        if (on_text && delta > 0) {font_size_t = Math.min(max_font_size, font_size_t += 1)};							
        window.SetProperty("text: font size: text", font_size_t);							

        get_font();							
        refresh_txt = true;	
        
        if (text_hiden){
            txt_x = ww - t_margin * 2 - h1_char_width - (scrollbar ? scrollbar_w + 10 : 0);
            txt_y = wh - (h1_text_row_height + t_margin * 2);
        }
        
        get_text_array();							
    }							
							
    if ((on_header_0 || on_header_1 || on_header_2 || on_text) && !ShiftDown && ControltDown){							
        if (delta < 0) {bg_transparence = Math.max(0, bg_transparence -= 10)};							
        if (delta > 0) {bg_transparence = Math.min(255, bg_transparence += 10)}; 							
        window.SetProperty("text bg transparence (0-255)", bg_transparence);							
        window.Repaint();							
    }							
							
    if (on_img && cycle_set && ShiftDown) {							
        if (delta < 0) {cycle = cycle <= 0 ? 0 : cycle - 5;};							
        if (delta > 0) {cycle = cycle >= 60 ? 60 : cycle + 5;};	
        window.SetProperty("auto cycle (sec)", cycle);							
        window.Repaint();							
    }
}							
								
function on_mouse_lbtn_down(x, y){							
    if (on_header_0 || on_header_1 || on_header_2 || on_info_text_btn || on_text){							
        on_text_down = true;							
        delta_x = x - txt_x;							
        delta_y = y - txt_y;							
    }

    if (on_seekbar){
        on_seekbar_down = true;
        seekbar_posy = (scroll * -1 / text_row_height) * seekbar_k;
        delta_y = seekbar_posy - y;
    }
    
    if (on_scrollbar && !on_seekbar){
        on_scrollbar_down = true;
        scroll = (y - t_y) / seekbar_k * text_row_height * -1; 
        scroll_check();	
    }

    if (tooltip_on){
        tooltip_on = false;
        window.Repaint();
    }
}

function on_mouse_lbtn_up(x,y){
    window.SetProperty("txt_x", txt_x);
    window.SetProperty("txt_y", txt_y);
    on_text_down = false;
    on_seekbar_down = false;
    on_scrollbar_down = false;
}

function lock_mode(){
    get_text_array();
    
    if (lock_loading){
        lock_artist = meta_artist;
        lock_album = meta_album;
        lock_title = meta_title;
    }
    if (!lock_loading){
        if (history_show){
            history_show = false;
            old_artist = "";
            history_arr = [];
            refresh_txt = true;
            get_text_array();
        }
        on_metadb_changed(); 
    }
}

function on_mouse_lbtn_dblclk (x, y){
    tooltip_x = x; 
    tooltip_y = y;
    
    if (on_header_0 || on_header_1){
        lock_loading = !lock_loading; 
        lock_mode();
    }
    
    if (on_text && lang_arr.length > 0 && !selected_item && !history_show){
        ShiftDown = utils.IsKeyPressed(VK_SHIFT) ? true : false;
        
        if (ShiftDown) {
            lang_idx = lang_idx <= 0 ? lang_arr.length - 1 : lang_idx - 1;
        } else {
            lang_idx = lang_idx >= lang_arr.length - 1 ? 0 : lang_idx + 1;
        }
        
        window.SetProperty("lang", lang_idx);
        path = artist_folder_path(clean(meta_artist));
        get_text(path, meta_artist, meta_album, meta_title);
        tooltip_text = get_text_menu(lang_arr[lang_idx]);
        tooltip && info_tooltip();
    }
    
    if (on_text && selected_item){
        if (selected_item == latest_release){
            data_main = 1;	
            data_other_idx = 3;
            meta_album = latest_release;
            get_img(meta_artist, meta_album, meta_title);	
        }
        
        if (selected_item == popular_this_week){
            data_main = 1;	
            data_other_idx = 4;
            meta_album = "";
            meta_title = popular_this_week; 
            get_img(meta_artist, meta_album, meta_title);	
        } 
        
        if (history_show){
            history_show = false;
            data_main = 0;
            lock_artist = selected_item;
            lock_album = "";
            lock_title = "";
            on_metadb_changed();
        }
    }        

    if (on_img){
        /*
        if (history_show && lock_loading){
            history_show = false;
            lock_loading = false;
        }
        */
        
        if (!history_show){
            data_main = data_main == 1 ? 0 : 1;
            window.SetProperty("data_main: bio or album, similar", data_main);
            get_img(meta_artist, meta_album, meta_title);
            
            switch(data_main) {
            case 0:
                tooltip_text = "artist";
                break;
            case 1:
                tooltip_text = data_other[data_other_idx][2].replace(/_/g," ");
                break;
            }
            meta_artist && tooltip && info_tooltip();
        }
    }
    
    if (on_info_text_btn){							
        info_text_idx = data_main == 0 ? 0 : data_main + data_other_idx;
        info_text_show = !window.GetProperty("info text " + info_text_idx);
        window.SetProperty("info text " + info_text_idx, info_text_show);
        scroll = 0, scroll_ = 0, scroll__ = 0, scroll___ = 0;
        refresh_txt = true;
        get_text_array();
    }
}

function on_mouse_mbtn_dblclk (x, y){
    !text_hiden && hide_text(x, y);
    text_hiden && restore_text(); 
    text_hiden = !text_hiden;
    window.SetProperty("txt hiden", text_hiden);
        
    window.SetProperty("txt_x", txt_x);
    window.SetProperty("txt_y", txt_y);
}

function on_mouse_leave() {
    window.SetCursor(IDC_ARROW);
    on_header_0 = false, on_header_1 = false, on_header_2 = false, on_info_text_btn = false, on_text = false, on_scrollbar = false, on_seekbar = false, on_img = false;
    window.Repaint(); 
}

function on_char(code) {
    if (history_show){
        e_char = String.fromCharCode(code);

        switch(code){
        case ESC:
            history_seach = "";
            get_history();
            break;
        case BACKSPACE:
            history_seach = history_seach.substring(0, history_seach.length - 1);
            get_history();
            break;
        case ENTER:
            break;
        default: // any character
            history_seach = history_seach + e_char;
            get_history();
            break;
        }
    }
}

function on_key_down(vkey) {
    switch(vkey){
    case VK_SHIFT:
        cycle_set = true;
        window.Repaint();
        break;
    }
    
    if (img_file_names.length > 1 && !cycle_set && !delay && !history_show){	
        switch(vkey){  
        case VK_LEFT:
            next_image(-1);
            break;
        case VK_RIGHT:
            next_image(1);
            break;  
        }
        
        if (vkey == VK_LEFT || vkey == VK_RIGHT){
            if (data_main != 0 && (data_other_idx == 0 || data_other_idx == 1 || data_other_idx == 2)){
                path = artist_folder_path(clean(meta_artist));
                get_text(path, meta_artist, meta_album, meta_title);
            }
            delay = true;							
            fdelay();							
            if (cycle > 0) cycle_step = 0;
        }        
    }
    
    if (text_height > text_visable_height){
        switch(vkey){
        case VK_UP:
            scroll_key_k = window.GetProperty(" scroll key k");
            scroll = scroll + text_row_height;
            scroll_check();	
            break;
        case VK_DOWN:
            scroll_key_k = window.GetProperty(" scroll key k");
            scroll = scroll - text_row_height;
            scroll_check();	
            break;
        case VK_HOME:
            scroll = 0;
            scroll_check();	
            break;
        case VK_END:
            scroll = -1 * (text_height - text_visable_height);
            scroll_check();	
            break;
        case VK_PAGE_UP: 
            scroll -= -1 * text_row_height * text_visable_rows; 
            scroll_check();	
            break;
        case VK_PAGE_DOWN :  
            scroll -= text_row_height * text_visable_rows; 
            scroll_check();	
            break;
        }
    }
}

function on_key_up(vkey) {
    switch(vkey){
    case VK_SHIFT:
        cycle_set = false; 
        if (cycle > 0) cycle_set_timer();
        if (cycle == 0) window.ClearInterval(cycle_timer);
        window.Repaint(); 
        break;
    }
}

function hide_text(x, y){  
    window.SetProperty("tmp_txt_x", txt_x);
    window.SetProperty("tmp_txt_y", txt_y);

    txt_x = ww - t_margin * 2 - h1_char_width - (scrollbar ? seekbar_w + 10 : 0);
    txt_y = wh - (h1_text_row_height + t_margin * 2);
    get_text_array();
}

function restore_text(){  
    txt_x = window.GetProperty("tmp_txt_x");
    txt_y = window.GetProperty("tmp_txt_y");
    get_text_array();
}

function on_size(){
    ww = window.Width;   
    wh = window.Height;
   
    txt_x = window.GetProperty("txt_x");
    txt_y = window.GetProperty("txt_y");

    txt_x = Math.round(Math.max(0, Math.min(txt_x, ww - t_margin * 2 - h1_char_width - (scrollbar ? seekbar_w + 10 : 0))));
    txt_y = Math.round(Math.max(0, Math.min(txt_y, wh - (h1_text_row_height + t_margin * 2))));

    refresh_txt = true;
    img_size_recount = false;
    def_img_size_recount = false;
    get_text_array();
}

function del_folders(n){
    var dir = fso.GetFolder(work_path);
    var e = new Enumerator( dir.SubFolders );
    try {
        for(; !e.atEnd(); e.moveNext() ) {
            var sub_folder = e.item().Name;
            if (sub_folder.indexOf("_download") < 0){
                if (sub_folder.indexOf(n) < 0){
                    fso.deleteFolder(work_path + sub_folder, true);	
                }	
            }   	
        }	
    } catch(e) {};	
}

function del_folder(n){
    if(!n) return;
    try {
        fso.deleteFolder(n, true);	
    } catch(e) {};	
}

function delete_empty_folders(){
    var dir = fso.GetFolder(work_path);

    var e = new Enumerator( dir.SubFolders );
    try {
        for(; !e.atEnd(); e.moveNext() ) {
            var sub_folder = objShellApp.NameSpace( e.item() + "\\" );
            var items = sub_folder.Items();
            var items_count = items.Count;

            if (!items_count){
                fso.deleteFolder(e.item(), true);
            }
        }
    } catch(e) {}
}
    
function calc_img_size(img){
    if(!img) return;
    
    ww = window.Width;   								
    wh = window.Height;								

    var size = {x:0, y:0, width:0, height:0, cx:0, cy:0, cwidth:0, cheight:0};
    
    var margin = img_margin ? img_margin : 0;;
    var border = img_border ? (img_border_width ? img_border_width : 0) : 0;
    var new_width = ww - border * 2 - margin * 2;
    var new_height = wh - border * 2 - margin * 2;
	
    switch(img_alignment_idx) {	
	case 0: // adjust
        var sw = new_width / img.Width;								
        var sh = new_height / img.Height;								
        var s = Math.min(sw, sh);								
        								
        var x = border + margin;								
        var y = border + margin;								
        								
        if (sw > sh) x = x + (new_width - img.Width * s) / 2;								
        else if (sw < sh) y = y + (new_height - img.height * s) / 2;								

        var width = img.Width * s;								
        var height = img.Height * s;								
        var cx = 0;								
        var cy = 0;								
        var cwidth = img.Width;								
        var cheight = img.Height;								
		break;						
				
    case 1: // adjust top - center								
        var sw = new_width / img.Width;								
        var sh = new_height / img.Height;								
        var s = Math.min(sw, sh);								
								
        var x = border + margin;								
        if (sw > sh) x = x + (new_width - img.Width * s) / 2;	
        var y = border + margin;							
        var width = img.Width * s;								
        var height = img.Height * s;								
        var cx = 0;								
        var cy = 0;								
        var cwidth = img.Width;								
        var cheight = img.Height;								
		break;	
        		
    case 2: // adjust top - left		
        var sw = new_width / img.Width;		
        var sh = new_height / img.Height;		
        var s = Math.min(sw, sh);		
        		
        var x = border + margin;		
        var y = border + margin;		
        var width = img.Width * s;		
        var height = img.Height * s;		
        var cx = 0;		
        var cy = 0;		
        var cwidth = img.Width;		
        var cheight = img.Height;		
		break;
		
	case 3: // centre	
		var sr = img.Width / img.Height;
		var dr = new_width / new_height;	
		if (sr < dr) {	
			var r = img.Width / new_width;
			var cheight = new_height * r;
			var cy = Math.round((img.Height - cheight) / 2);
			var cwidth = img.Width;
			var cx = 0;
		} else {	
			var r = img.Height / new_height;
			var cwidth = new_width * r;
			var cx = Math.round((img.Width - cwidth) / 2);
			var cheight = img.Height;
			var cy = 0;
		}	
        var x = border + margin;		
        var y = border + margin;			
        var width = new_width;			
        var height = new_height;			
		break;	
        			
	case 4: // centre - top		
        var sr = img.Width / img.Height;								
        var dr = new_width / new_height;								
        if (sr < dr) {
            var r = img.Width / (new_width);								
            var cheight = new_height * r;		
            var cy = 0;								
            var cwidth = img.Width;								
            var cx = 0;								
        } else {
            var r = img.Height / new_height;								
            var cwidth = new_width * r;	
            var cx = Math.round((img.Width - cwidth) / 2);								
            var cheight = img.Height;								
            var cy = 0;								
		}						
        var x = border + margin;									
        var y = border + margin;								
        var width = new_width;								
        var height = new_height;								
		break;			
	case 5: // stretch		
        var x = border + margin;									
        var y = border + margin;									
        var width = new_width;								
        var height = new_height;								
        var cx = 0;								
        var cy = 0;								
        var cwidth = img.Width;								
        var cheight = img.Height;								
		break;	
    }		
    		
    size.x = Math.round(x);								
    size.y = Math.round(y); 
    size.width = Math.round(width); 								
    size.height = Math.round(height); 	
    size.cx = Math.round(cx); 								
    size.cy = Math.round(cy);								
    size.cwidth = Math.round(cwidth);								
    size.cheight = Math.round(cheight);								
    return size;	
}

function copy_files(select_file){
    var destination_path;
    var tmp_destination_path;
    var tmp_files = [];
    var tmp_artist = meta_artist;
    var tmp_folder;

    switch(data_main) {
    case 0:
        tmp_folder = "artist";
        break;
    case 1:
        tmp_folder = data_other[data_other_idx][2];
        break;
    }

    if (metadb.RawPath.indexOf("file") < 0) {
        tmp_destination_path = fb.ProfilePath + "tmp_lastFm_img\\";
    } else {
        tmp_destination_path = directory_path + "\\" + tmp_folder + "\\";
    }   
    
    var nl = "\" + chr(10) + \"";

    if (select_file == 0){
        tmp_files.push(img_file_names[img_selected]);
        var input_box_text = "Copy  " + nl + nl + get_fnext(tmp_files[0]) + nl + "file to";
    } else {
        tmp_files = img_file_names;
        var input_box_text = "Copy  " + nl + nl + tmp_artist + " * " + tmp_folder + ".jpg" + nl + "files to";
    }

    var string = input_box(input_box_text, tmp_destination_path, "Foobar 2000");
    if (!/\S/.test(string)) copy_files();
    
    if (string){
        destination_path = folder_exists(string);
        if (fso.FolderExists(destination_path)) {
            copy_files_to_folder(destination_path, tmp_files, tmp_folder);
        }
    }
}

function copy_files_to_folder(path, img_file_names, folder){
    for (i in img_file_names) {
        try {
            fso.CopyFile (img_file_names[i], path  , 1);
        } catch(e) {}
    }
}

function input_box(p_text, d_text, w_title){
    vbe = new ActiveXObject('ScriptControl');//*
    vbe.Language = 'VBScript';//*
    return vbe.eval( "InputBox(\"" + p_text + "\",\"" + w_title + "\",\"" + d_text + "\")");
}

function clean_path_name(n) {
    if (!n) return;
    return n.replace(/[\/\:\*\?\"\<\>\|]/g,'');
}

function folder_exists(n) {
    var driver = fso.GetDriveName(n);
    if (!fso.DriveExists(driver)) {
        return "";
    } else {
        var p = "";
        var split_string = [];
        split_string = n.replace(/\\$/g, "").split("\\");

        for (var i = 1; i < split_string.length; i += 1) {
            p = p + clean_path_name(split_string[i]) + "\\";
            try {
                if(!fso.FolderExists(driver + "\\" + p)) fso.CreateFolder(driver + "\\" + p);
            } catch(e) {};
        }
        return driver + "\\" + p;
    }
}

function naturalSort(stringArray) {
    var xor = function(a, b) {
        return a ? !b : b;
    }
    var isDigit = function(chr) {
        var charCode = function(ch) {
            return ch.charCodeAt(0);
        };
        var code = charCode(chr);
        return (code >= charCode('0')) && (code <= charCode('9'));
    }
    var splitString = function(str) {
        var from = 0;   
        var index = 0;
        var count = 0;  
        var splitter = {};

        splitter.count = function () {
            return count;
        }
        splitter.next = function() {
            if (index === str.length) {
                return null;
            }
            while(++index) {
                var currentIsDigit = isDigit(str.charAt(index - 1));  
                var nextChar = str.charAt(index);
                var currentIsLast = (index === str.length);
                var isBorder = currentIsLast || xor(currentIsDigit, isDigit(nextChar));        
                if (isBorder) {
                var part = str.slice(from, index);
                    from = index;
                    count++;
                    return {
                        IsNumber: currentIsDigit,
                        Value: currentIsDigit ? Number(part) : part
                    }
                }
            } 
        } 
        return splitter;
    }
    var compareStrings = function(str1, str2) {
        var compare = function(a, b) {  
            return (a < b) ? -1 : (a > b) ? 1 : 0;
        }
        var splitter1 = splitString(str1);
        var splitter2 = splitString(str2);
        while (true) {
            var first = splitter1.next();
            var second = splitter2.next();
            if (null !== first && null !== second) {
                if (xor(first.IsNumber, second.IsNumber)) {
                    return first.IsNumber ? -1 : 1;        
                } else {                    
                    var comp = compare(first.Value, second.Value);    
                    if (comp != 0) {
                        return comp;
                    }
                }						
            } else {						
                return compare(splitter1.count(), splitter2.count());						
            }						
        }						
    }						
    var arr = stringArray;						
    return arr.sort(compareStrings);  						
}

function delete_empty_folders(){
    var dir = fso.GetFolder(work_path);
    var e = new Enumerator( dir.SubFolders );

    try {
        for(; !e.atEnd(); e.moveNext() ) {
            var sub_folder = objShellApp.NameSpace( e.item() + "\\" );
            var items = sub_folder.Items();
            var items_count = items.Count;

            if (items_count == 0){
                fso.deleteFolder(e.item(), true);
            }
        }
    } catch(e) {}
}

function get_lastFm_meta_artist_img(path, t_artist){
    var xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP");   						
    var url1 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(t_artist) + "/+images");  	
    xmlhttp1.open("GET", url1, true ); 
    xmlhttp1.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");	
    xmlhttp1.send(null);     						
    xmlhttp1.onreadystatechange = function () { 
        if (xmlhttp1.readyState == 4) {
            if (xmlhttp1.status == 200) {  
                doc.open();     
                var div = doc.createElement("div");
                div.innerHTML = xmlhttp1.responsetext;
                var d = div.getElementsByTagName("div");	
                var img = div.getElementsByTagName("img");
                
                var msg = "";

                for (i = 0; i < d.length; i++) {  							
                    if (d[i].className == "no-data-message"){   // "We don't have any photos for this artist yet."  							
                       msg = d[i].innerText;
                    }							
                }

                no_img_msg = msg ? msg + "\n\n" : "";
                
                var img_urls = [];

                for (i = 0; i < img.length; i++) {   
                    if (img[i].src.indexOf("https://img2-ak.lst.fm/i/u/avatar170s") == 0 || img[i].src.indexOf("https://lastfm-img2.akamaized.net/i/u/avatar170s") == 0) {
                        img_urls.push(img[i].src.replace("avatar170s", quality[quality_idx][1]));
                    }     
                }
                						
                for (i = 0; i < Math.min(img_urls.length, limit); i++) {  
                    var img_file = path + "\\" + clean(t_artist) + "_"  + i + "_artist.jpg";
                    if (!fso.FileExists(img_file)){
                        WshShell.Run(vbs + " " + img_urls[i] + " " + "\"" + img_file + "\"", 0, false);
                    }	
                }
                
                doc.close();	
                
                if (img_urls.length > 0 && !g_img) {
                    get_files_if_loaded(path, t_artist);
                    //image_upload_delay(path, t_artist);
                } else {                   
                    get_lastFm_artist_info_text(path, "file", t_artist);
                }
            } else {
                get_lastFm_artist_info_text(path, "file", t_artist);
            }
        } 						
    }     						
}						

//function get_lastFm_popular_albums(path, t_artist){	
function get_lastFm_album_img(path, t_artist){						
    var xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");   						
    //var url2 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(t_artist) + "/+" + data_other[data_other_idx][1]);  						
    var url2 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(t_artist) + "/+albums");  						
    xmlhttp2.open("GET", url2, true );  
    xmlhttp2.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp2.send(null);     
    xmlhttp2.onreadystatechange = function () { 
        if (xmlhttp2.readyState == 4) { 
            if (xmlhttp2.status == 200) {  
                doc.open();     
                var div = doc.createElement("div");
                div.innerHTML = xmlhttp2.responsetext;
                var p = div.getElementsByTagName("p");
                var img = div.getElementsByTagName("img");
                
                var msg = "";

                for (i = 0; i < p.length; i++) {  							
                    if (p[i].className == "wiki-cta link-block js-link-block"){  	// Do you know any background info about this album?						
                        msg = p[i].innerText;
                    }							
                }

                no_img_msg = msg;
                
                var urls = [];
                var img_urls = [];
                var album_name = [];
                var color = [];
                var font = [];
                var tmp_data_2 = [], tmp_data_3 = [];
                var data_1 = [], data_2 = [], data_3 = [];	
                
                for (i = 0; i < p.length; i++) {   
                    if (p[i].className == "resource-list--release-list-item-aux-text resource-list--release-list-item-listeners" ){ // album: listeners
                        tmp_data_2.push(p[i].innerHTML.replace(/\,|(&nbsp;)/g, ' '));
                    } 
                    if (p[i].className == "resource-list--release-list-item-aux-text" ){ // album: release date 
                        tmp_data_3.push(p[i].innerHTML.replace(/\,|(&nbsp;)/g, ' '));
                    } 
                }                    

                for (i = 0; i < img.length; i++) {
                    //if (img[i].src.indexOf("https://lastfm-img2.akamaized.net/i/u/300x300") == 0){  
                    if (img[i].src.indexOf("https://lastfm-img2.akamaized.net/i/u/300x300") == 0 && img[i].alt.indexOf("Avatar for") < 0){  
                        urls.push(img[i].src);
                        album_name.push(img[i].alt);        // album: name  
                    }
                }
					
                for (i = 0; i < urls.length; i++) { 
                    if (urls[i].indexOf("c6f59c1e5e7240a4c0d427abd71f3dbb") < 0 && urls[i].indexOf("2a96cbd8b46e442fc41c2b86b821562f") < 0) {	
                        img_urls.push(urls[i].replace("300x300", quality[quality_idx][1]));
                        
                        data_1.push(album_name[i]);     // album: name	
                        data_2.push(tmp_data_2[i]);     // album: listeners						
                        data_3.push(tmp_data_3[i]);     // album: release date	
                    }						
                }
                
                color.push("h1_color", "h1_color");
                font.push("t2_font", "t2_font");

                for (i = 0; i < Math.min(img_urls.length, limit); i++) {  
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_album_info.ini", data_other[data_other_idx][2] + " : name", i, data_1[i]);	
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_album_info.ini", data_other[data_other_idx][2] + " : info : " + lang_arr[lang_idx], i, data_2[i] + "*" + data_3[i]);

                    utils.WriteINI( path + "\\" + clean(t_artist) + "_album_info.ini", data_other[data_other_idx][2] + " : info : " + lang_arr[lang_idx], i + "_c", color.join("*"));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_album_info.ini", data_other[data_other_idx][2] + " : info : " + lang_arr[lang_idx], i + "_f", font.join("*"));

                    var img_file = path + "\\" + clean(t_artist) + "_"  + clean(data_1[i]) + ".jpg";    
                    if (!fso.FileExists(img_file )){
                        WshShell.Run(vbs + " " + img_urls[i] + " " + "\"" + img_file + "\"", 0, false);
                    }
                } 
                
                doc.close();	

                if (img_urls.length > 0 && !g_img) {
                    get_files_if_loaded(path, t_artist);
                    //image_upload_delay(path, t_artist);
                } else {
                    get_text(path, t_artist);
                }
            } else {
                get_text(path, t_artist);
            }
        } 					
    }   
}					

function get_lastFm_artist_info_text(path, file, t_artist){
    var xmlhttp9 = new ActiveXObject("Microsoft.XMLHTTP");   
    var url9 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(t_artist)); 
    xmlhttp9.open("GET", url9, true ); 
    xmlhttp9.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp9.send(null);     
    xmlhttp9.onreadystatechange = function () {
        if (xmlhttp9.readyState == 4) {
            if (xmlhttp9.status == 200) { 
                doc.open();     
                var div = doc.createElement("div");
                div.innerHTML = xmlhttp9.responsetext;
                var p = div.getElementsByTagName("p");
                var a = div.getElementsByTagName("a");
                var li = div.getElementsByTagName("li");
                var h4 = div.getElementsByTagName("h4");
                var abbr = div.getElementsByTagName("abbr");
                var a = div.getElementsByTagName("a");
                
                var data =[];
                var color = [];            
                var font = []; 
                
                ////////////////////////////////////////////////////////////////////////////////////

                var rank_text = "";
                var rank_value = "";
                
                for (i = 0; i < p.length; i++) {
                    if (p[i].className.replace(/[\s]/g, "") == "tooltip-dark header-new-chart-position-tooltip".replace(/[\s]/g, "")) {
                        rank_text = p[i].innerText.replace(/\./g, "");
                    }
                } 
                
                for (i = 0; i < a.length; i++) {
                    if (a[i].className.replace(/[\s]/g, "") == "header-new-chart-position-number disclose-trigger".replace(/[\s]/g, "")) {
                        rank_value = a[i].innerText;
                    }
                }           
                
                if (rank_text && rank_value) {
                    var rank_data = [];
                    var rank_color = [];
                    var rank_font = [];
                    
                    rank_data.push(rank_text, rank_value, "", "");
                    rank_color.push("h1_color", "t_color", "", "");
                    rank_font.push("t2_font", "t_font", "", "");

                    utils.WriteINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx] + "_rank", rank_data.join("*"));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx] + "_rank_c", rank_color.join("*"));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx] + "_rank_f", rank_font.join("*"));
                } 

                ////////////////////////////////////////////////////////////////////////////////////
                
                var tag = "";

                for (i = 0; i < li.length; i++) {						
                    if (li[i].className == "tag") {     //  classic rock rock southern rock 60s folk 70s
                        tag = tag + li[i].innerText + "; ";
                    }
                } 

                if (tag) {
                    tag = tag.substring(0, tag.length - 2);
                    data.push(tag, "");
                    color.push("t_color", "");
                    font.push("t2_font", ""); 
                } 

                ////////////////////////////////////////////////////////////////////////////////////
                
                var tmp_data_1 = [], tmp_data_2 = [];;

                for (i = 0; i < h4.length; i++) {
                    if (h4[i].className == "header-metadata-tnew-title") {    // Scrobbles, Listeners   NEW
                        tmp_data_1.push(h4[i].innerText);
                    }
                }

                for (i = 0; i < abbr.length; i++) {
                    if (abbr[i].className == "intabbr js-abbreviated-counter") {     // 57,404,270, 2,314,768   NEW
                        tmp_data_2.push(abbr[i].title.replace(/,/g, " "));
                    }
                } 
                
                for (i = 0; i < tmp_data_1.length / 2; i++) {
                    data.push(tmp_data_1[i], tmp_data_2[i]);
                    color.push("h1_color", "t_color");
                    font.push("t2_font", "t_font"); 
                } 

                if (tmp_data_1.length > 0) {
                    data.push("");
                    color.push("");
                    font.push("");  
                }

                ////////////////////////////////////////////////////////////////////////////////////
                
                var tmp_data_1 = [], tmp_data_2 = [];
                
                
                for (i = 0; i < h4.length; i++) {						
                    if (h4[i].className == "artist-header-featured-items-item-header") {       // Latest release, Popular this week
                        tmp_data_1.push(h4[i].innerText);
                    }
                }

                for (i = 0; i < a.length; i++) {						
                    if (a[i].className == "link-block-target") {      // Live At Woodstock, Fortunate Son, 
                        tmp_data_2.push(a[i].innerText);
                    }
                }           

                utils.WriteINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), "latest_release", tmp_data_2[0]);
                utils.WriteINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), "popular_this_week", tmp_data_2[1]);

                for (i = 0; i < tmp_data_1.length; i++) {
                    data.push(tmp_data_1[i], tmp_data_2[i]);
                    color.push("h1_color", "t_color");
                    font.push("t2_font", "t_font"); 
                } 

                utils.WriteINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx], data.join("*"));
                utils.WriteINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx] + "_c", color.join("*"));
                utils.WriteINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), lang_arr[lang_idx] + "_f", font.join("*"));

                doc.close();

                get_text(path, t_artist);
            } else {
                get_text(path, t_artist);
            }
        }
    }     
}

function get_lastFm_bio_text(path, file, t_artist){					
    xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");					
    url3 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(t_artist) + "/+wiki");	
    xmlhttp3.open("GET", url3, true);					
    xmlhttp3.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp3.send(null);							
    xmlhttp3.onreadystatechange = function () {							
        if (xmlhttp3.readyState == 4) {							
            if (xmlhttp3.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp3.responsetext;
                var li = div.getElementsByTagName("li");
                var ddiv = div.getElementsByTagName("div");	
                
                var data = [];
                
                if (data_main == 0) {
                    for (i = 0; i < li.length; i++) {	
	                    if (li[i].className == "factbox-item") {    // Years Active ...
		                    if (li[i].innerText) data.push(li[i].innerText.replace(/(\d+)/, " $1")); 
                            break;
	                    }
                    }                    
                    header_2 = data;
                    utils.WriteINI( path + "\\" + clean(meta_artist) + "_artist_info.ini", clean_ini(clean(t_artist)) + " : years active", lang_arr[lang_idx], data);
                }

                var t = "";							
                var save_text = false;	

                for (i = 0; i < ddiv.length; i++) {							
                    if (ddiv[i].className == "wiki") {							
                        t = ddiv[i].innerHTML;                  // bio or "We don't have a wiki here yet..."
                        save_text = t.indexOf('wiki-content') > 0 ? true : false;							
                        t = trim(strip_tags(t));							
                        break;							
                    } 							
                } 

                doc.close();							
            } 
            if (t) {
                text = t; 
                save_text && save_txt_file(t, file);
            } else {
                text = get_text_nf(lang_arr[lang_idx]);
            }
            get_text_array();
        }
    }							
}							
							
function get_lastFm_album_text(path, file, t_artist, t_album){	
    xmlhttp4 = new ActiveXObject("Microsoft.XMLHTTP");							
    url4 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(t_artist) + "/" + encodeURIComponent(t_album).replace("%2B", "%252B") + "/+wiki");
    xmlhttp4.open("GET", url4, true);							
    xmlhttp4.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");							
    xmlhttp4.send(null);							
    xmlhttp4.onreadystatechange = function () {							
        if (xmlhttp4.readyState == 4) {							
            if (xmlhttp4.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp4.responsetext;							
                var div = div.getElementsByTagName("div");						
                
                var t = "";						
                var save_text = false;						
                						
                for (i = 0; i < div.length; i++) {						
                    if (div[i].className == "wiki") {						
                        t = div[i].innerHTML;	
                        save_text = t.indexOf('wiki-content') > 0 ? true : false;						
                        t = trim(strip_tags(t));						
                        break;						
                    } 						
                }

                doc.close();
            }
            if (t) {
                text = t; 
                save_text && save_txt_file(t, file);
            } else {
                text = get_text_nf(lang_arr[lang_idx]);
            }
            get_text_array();
        }
    }						
}						
						
function get_lastFm_similar_img(path, t_artist){	
    var xmlhttp5 = new ActiveXObject("Microsoft.XMLHTTP");   						
    var url5 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(t_artist) + "/+similar");  					
    xmlhttp5.open("GET", url5, true );  
    xmlhttp5.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");	
    xmlhttp5.send(null);     					
    xmlhttp5.onreadystatechange = function () { 					
        if (xmlhttp5.readyState == 4) { 					
            if (xmlhttp5.status == 200) {  					
                doc.open();     					
                var div = doc.createElement("div");					
                div.innerHTML = xmlhttp5.responsetext;
                var p = div.getElementsByTagName("p");	 
                var a = div.getElementsByTagName("a");	
                var img = div.getElementsByTagName("img");	

                var msg = "";

                for (i = 0; i < p.length; i++) {  							
                    if (p[i].className == "no-data-message"){  							
                       msg = p[i].innerHTML;
                    }							
                }
                
                no_img_msg = msg ? msg + "\n\n" : "";
                
                var tmp_data = [];
                var data = [];
                					
                for (i = 0; i < a.length; i++) {  							
                    if (a[i].className == "link-block-target"){    // similar artist names 							
                        tmp_data.push(a[i].innerHTML.replace(/(&amp;)/g,'&'));	
                    }							
                } 							

                var urls = [];
                var img_urls = [];	

                for (i = 0; i < img.length; i++) {
                    if (img[i].src.indexOf("https://lastfm-img2.akamaized.net/i/u/300x300") == 0){  
                        urls.push(img[i].src);
                    }
                }
                        
                for (i = 0; i < urls.length; i++) { 
                    if (urls[i].indexOf("c6f59c1e5e7240a4c0d427abd71f3dbb") < 0 && urls[i].indexOf("2a96cbd8b46e442fc41c2b86b821562f") < 0) {	
                        img_urls.push(urls[i].replace("300x300", quality[quality_idx][1]));
                        
                        data.push(tmp_data[i]);     // similar artist names if image exist	
                    }						
                }

                for (i = 0; i < Math.min(img_urls.length, limit); i++) { 	
                    if (img_urls[i].indexOf("c6f59c1e5e7240a4c0d427abd71f3dbb") < 0 && img_urls[i].indexOf("2a96cbd8b46e442fc41c2b86b821562f") < 0) {	                    
                        utils.WriteINI( path + "\\" + clean(t_artist) + "_artist_info.ini", data_other[data_other_idx][2] + " : name", i, data[i]); 							
 
                        var img_file = path + "\\" + clean(t_artist) + "_"  + i + "_" + data_other[data_other_idx][2] + ".jpg";
                        WshShell.Run(vbs + " " + img_urls[i] + " " + "\"" + img_file + "\"", 0, false);	
                    }    
                } 
                
                doc.close();	

                if (img_urls.length > 0) {
                    get_files_if_loaded(path, t_artist);
                    //image_upload_delay(path, t_artist);
                } else {
                    get_text(path, t_artist);
                }
            } else {
                get_text(path, t_artist);
            }
        } 					
    }     					
}

function get_lastFm_meta_album_img(path, t_artist, t_album){	
    var xmlhttp6  = new ActiveXObject("Microsoft.XMLHTTP");   
    var url6 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(t_artist) + "/" + encodeURIComponent(t_album));  
    xmlhttp6.open("GET", url6, true ); 
    xmlhttp6.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp6.send(null);     
    xmlhttp6.onreadystatechange = function () { 
        if (xmlhttp6.readyState == 4) { 
            if (xmlhttp6.status == 200) { 
                doc.open();     
                var div = doc.createElement("div");
                div.innerHTML = xmlhttp6.responsetext;
                var li = div.getElementsByTagName("li");
                var h4 = div.getElementsByTagName("h4");
                var abbr = div.getElementsByTagName("abbr");
                var dt = div.getElementsByTagName("dt");                                
                var dd = div.getElementsByTagName("dd");              
                var img = div.getElementsByTagName("img");

                var data = [];
                var color = [];
                var font = [];
                
                var tag = "";
                
                for (i = 0; i < li.length; i++) {						
                    if (li[i].className == "tag") {
                        tag = tag + li[i].innerText + "; ";
                    }
                } 

                if (tag) {
                    tag = tag.substring(0, tag.length - 2);
                    data.push(tag, "");
                    color.push("t_color", "");
                    font.push("t2_font", "");
                }              
                
                var tmp_data_1 = [], tmp_data_2 = [];
                
                for (i = 0; i < h4.length; i++) {
                    if (h4[i].className == "header-metadata-tnew-title") {  // scrobbles  isteners -NEW
                        tmp_data_1.push(h4[i].innerText);
                    }
                }

                for (i = 0; i < abbr.length; i++) {	
                    if (abbr[i].className == "intabbr js-abbreviated-counter") {    // 13,294,523  512,404 -NEW
                        tmp_data_2.push(abbr[i].title.replace(/,/g, " "));
                    }
                }  

                for (i = 0; i < tmp_data_1.length / 2; i++) {
                    data.push(tmp_data_1[i], tmp_data_2[i]);
                    color.push("h1_color", "t_color");
                    font.push("t2_font", "t_font"); 
                } 

                if (tmp_data_1.length > 0){      // empty line
                    data.push("");
                    color.push("");
                    font.push("");
                }

                var tmp_data_1 = [], tmp_data_2 = [];
                
                for (i = 0; i < dt.length; i++) {						
                    if (dt[i].className == "catalogue-metadata-heading") {  // Length,  Release Date
                        if (dt[i].innerText) tmp_data_1.push(dt[i].innerText);
                    }
                }

                for (i = 0; i < dd.length; i++) { 
                    if (dd[i].className == "catalogue-metadata-description"){   // 8 tracks, 33:00,  5 July 1968
                        if (dd[i].innerText) tmp_data_2.push(dd[i].innerText);
                    }
                }               
                
                for (i = 0; i < tmp_data_1.length / 2; i++) {
                    data.push(tmp_data_1[i], tmp_data_2[i]);
                    color.push("h1_color", "t_color");
                    font.push("t2_font", "t_font");
                }  
                
                var img_urls = [];
                
                for (i = 0; i < img.length; i++) {
                    if (img[i].src.indexOf("https://lastfm-img2.akamaized.net/i/u/500x500") == 0) {
                    //if (img[i].src.indexOf("https://lastfm-img2.akamaized.net/i/u/174s") == 0 && img[i].src.indexOf("c6f59c1e5e7240a4c0d427abd71f3dbb") < 0) { 
                        img_urls.push(img[i].src.replace("500x500", quality[quality_idx][1])); //ar0
                    }
                }        

                if (img_urls.length) {
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_album_info.ini", clean_ini(clean(t_album)), lang_arr[lang_idx], data.join("*"));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_album_info.ini", clean_ini(clean(t_album)), lang_arr[lang_idx] + "_c", color.join("*"));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_album_info.ini", clean_ini(clean(t_album)), lang_arr[lang_idx] + "_f", font.join("*"));
      
                    var img_file = path + "\\" + clean(t_artist) + "_" + clean(t_album) + ".jpg";  

                    if (!fso.FileExists(img_file)){
                        if (g_img) g_img.Dispose();
                        g_img = null;   
                        images = [];			
                        img_file_names = [];	
                        WshShell.Run(vbs + " " + img_urls[0] + " " + "\"" + img_file + "\"", 0, false);
                    }
                }

                doc.close();
                
                if (img_urls.length > 0 && !g_img) {
                    get_files_if_loaded(path, t_artist, t_album);
                    //image_upload_delay(path, t_artist, t_album);
                } else {
                    get_text(path, t_artist, t_album);
                }
            } else {
                get_text(path, t_artist, t_album);
            }
        } 
    }     
}

function get_lastFm_meta_title_img(path, t_artist, t_album, t_title){
    var q1 = encodeURIComponent(t_artist) + "/";
    var q2 = t_album ? encodeURIComponent(t_album).replace("%2B", "%252B") + "/" : "_/";
    var q3 = t_title ? encodeURIComponent(t_title) : "";
    xmlhttp7 = new ActiveXObject("Microsoft.XMLHTTP");
    url7 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + q1 + q2 + q3);
    xmlhttp7.open("GET", url7, true);							
    xmlhttp7.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");							
    xmlhttp7.send(null);							
    xmlhttp7.onreadystatechange = function () {							
        if (xmlhttp7.readyState == 4) {							
            if (xmlhttp7.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp7.responsetext;
                var h4 = div.getElementsByTagName("h4");
                var abbr = div.getElementsByTagName("abbr");
                var ddiv = div.getElementsByTagName("div");	
                var img = div.getElementsByTagName("img");

                var album_name = "";
                var data = [];
                var color = []; 
                var font = []; 
                
                for (i = 0; i < h4.length; i++) {		 // from the album - album name				
                    if (h4[i].className == "source-album-name") {
                        album_name = h4[i].innerText;						
                        data.push(album_name.toUpperCase(), "");
                        color.push("t_color", "");
                        font.push("t_font", "");
                        break;						
                    }
                }
                
                var tmp_data_1 = [], tmp_data_2 = [];
         
                for (i = 0; i < h4.length; i++) {
                    if (h4[i].className == "header-metadata-tnew-title") {    // Listeners	Scrobbles
                        tmp_data_1.push(h4[i].innerText);
                    }
                }
               
                for (i = 0; i < abbr.length; i++) {
                    if (abbr[i].className == "intabbr js-abbreviated-counter") {   // 2,426,608  413,322
                        tmp_data_2.push(abbr[i].title.replace(/,/g, " "));
                    }
                }

                for (i = 0; i < tmp_data_1.length / 2; i++) {
                    data.push(tmp_data_1[i], tmp_data_2[i]);
                    color.push("h1_color", "t_color");
                    font.push("t2_font", "t_font"); 
                } 

                /*
                    <dt class="catalogue-metadata-heading">Length</dt>
                    <dd class="catalogue-metadata-description">
                        2:50
                */
                
                /*
                //////////////////////////////////////////////////////////////////////////////

                if (tmp_data_1.length > 0) {      // empty line
                        data.push("");
                        color.push("");
                        font.push("");
                }
                */

                var msg = "";
                
                for (i = 0; i < ddiv.length; i++) {						
                    if (ddiv[i].className == "source-album-nodata") {   // "We donвЂt have an album for this track yet."
                        msg = ddiv[i].innerText;
                        break;						
                    }
                }
                
                no_img_msg = msg ? msg + "\n\n" : "";   

                //////////////////////////////////////////////////

                /*
                <div class="
                    lyrics-snippet-wrap
                    "
                >
                        <p class="lyrics-snippet">The years have been many, the years have been long<br/>But at last I'm returning to daddy and home<br/>He's looking my way though he hardly can see<br/>God bless&hellip;</p>
        
                        <p class="lyrics-snippet-more-link">
                            <a href="/music/Johnny+Cash/_/Snow+in+His+Hair/+lyrics">
                                View full lyrics
                            </a>
                        </p>
                </div>

                var lyrics_url = "";
                
                var a = div.getElementsByTagName("a");

                for (i = 0; i < a.length; i++) {						
                    if (a[i].className == "external-link") { 
                        lyrics_url = a[i].href + ".html";
                    }
                }
                */
                
                var img_urls = [];

                for (i = 0; i < img.length; i++) {
                    if (img[i].src.indexOf("https://lastfm-img2.akamaized.net/i/u/300x300") == 0) { 
                    //if (img[i].src.indexOf("https://lastfm-img2.akamaized.net/i/u/174s") == 0 && img[i].src.indexOf("c6f59c1e5e7240a4c0d427abd71f3dbb") < 0) { 
                        img_urls.push(img[i].src.replace("300x300", quality[quality_idx][1]));
                    }
                }
                
                if (img_urls.length) {
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "album", clean(album_name));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), lang_arr[lang_idx], data.join("*"));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), lang_arr[lang_idx] + "_c", color.join("*"));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), lang_arr[lang_idx] + "_f", font.join("*"));
                    
                    //utils.WriteINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "LastFm_lyrics_url", lyrics_url);

                    var img_file = path + "\\" + clean(t_artist) + "_" + clean(album_name) + ".jpg";

                    if (album_name && !fso.FileExists(img_file)){
                        
                        if (g_img) g_img.Dispose();
                        g_img = null;   
                        images = [];			
                        img_file_names = [];	
                        WshShell.Run(vbs + " " + img_urls[0] + " " + "\"" + img_file + "\"", 0, false);
                    }
                }
                
                doc.close();
                
                if (img_urls.length > 0 && !g_img && album_name) {
                    get_files_if_loaded(path, t_artist, album_name, t_title);
                    //image_upload_delay(path, t_artist, album_name, t_title);
                } else {
                    get_text(path, t_artist, t_album, t_title);
                }
            } else {
                get_text(path, t_artist, t_album, t_title);
            }
        }
    }						
}

function get_lastFm_meta_title_text(path, file, t_artist, t_album, t_title){
    var q1 = encodeURIComponent(t_artist) + "/";
    var q2 = t_album ? encodeURIComponent(t_album).replace("%2B", "%252B") + "/" : "_/";
    var q3 = t_title ? encodeURIComponent(t_title) : "_";
    xmlhttp8 = new ActiveXObject("Microsoft.XMLHTTP");							
    url8 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + q1 + q2 + q3 + "/+wiki");
    xmlhttp8.open("GET", url8, true);							
    xmlhttp8.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");							
    xmlhttp8.send(null);							
    xmlhttp8.onreadystatechange = function () {							
        if (xmlhttp8.readyState == 4) {							
            if (xmlhttp8.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp8.responsetext;							
                var div = div.getElementsByTagName("div");						
                var t = "";						
                						
                var save_text = false;						

                for (i = 0; i < div.length; i++) {						
                    if (div[i].className == "wiki") {						
                        t = div[i].innerHTML;	
                        save_text = t.indexOf('wiki-content') > 0 ? true : false;						
                        t = trim(strip_tags(t));						
                        break;						
                    } 						
                } 

                doc.close();
            }
            if (t) {
                text = t; 
                save_text && save_txt_file(t, file);
            } else {
                text = get_text_nf(lang_arr[lang_idx]);
            }
            get_text_array();
        }
    }						
}

function metrolyrics_query(n){
    if (!n) return;
    n = n.toLocaleLowerCase();
    n = n.replace(/&/g, "and").replace(/\s/g, "-").replace(/\'/g, "");
    return n;
}

function get_metrolyrics_meta_lyrics_text(path, file, t_artist, t_title){
    xmlhttp9 = new ActiveXObject("Microsoft.XMLHTTP");	
    url = ("http://www.metrolyrics.com/" + metrolyrics_query(t_title) + "-lyrics-" + metrolyrics_query(t_artist) + ".html");
    xmlhttp9.open("GET", url, true);							
    xmlhttp9.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");							
    xmlhttp9.send(null);							
    xmlhttp9.onreadystatechange = function () {							
        if (xmlhttp9.readyState == 4) {	
            if (xmlhttp9.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp9.responsetext;							
                var p = div.getElementsByTagName("p");
                
                var t = "";	
                var tmp = [];
                var data = [];
                var color = [];
                var font = []; 

                var site_name = url.replace(/.*\/{2}/g, "").replace(/\/.*/g, "");            
                
                for (i = 0; i < p.length; i++) {	
                    if (p[i].className == "verse") {
                        tmp.push(p[i].innerHTML);
                    } 						
                } 

                t = strip_tags(tmp.join("\n\n"));
                
                if (t){
                    data.push(site_name);
                    color.push("h1_color");
                    font.push("t2_font");
                
                    info_text_arr = data;
                    info_text_color = color;
                    info_text_font = font;

                    utils.WriteINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "lyrics", data.join("*"));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "lyrics_c", color.join("*"));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "lyrics_f", font.join("*"));
                }
                
                doc.close();
            }
            if (t) {
                text = t; 
                save_txt_file(t, file);
                get_text_array();
            } else {
                get_azlyrics_meta_lyrics_text(path, file, t_artist, t_title)
                //text = get_text_nf(lang_arr[lang_idx]);
            }
            //get_text_array();
        }
    }						
}

function azlyrics_query(n){
    if (!n) return;
    n = n.toLocaleLowerCase();
    n = n.replace(/&/g, "and").replace(/\W/g, "");
    return n;
}

function get_azlyrics_meta_lyrics_text(path, file, t_artist, t_title){
    xmlhttp10 = new ActiveXObject("Microsoft.XMLHTTP");
    url10 = "https://www.azlyrics.com/lyrics/" + azlyrics_query(t_artist) + "/" + azlyrics_query(t_title) + ".html"	
    xmlhttp10.open("GET", url10, true);							
    xmlhttp10.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");							
    xmlhttp10.send(null);							
    xmlhttp10.onreadystatechange = function () {							
        if (xmlhttp10.readyState == 4) {							
            if (xmlhttp10.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp10.responsetext;							
                var h = div.getElementsByTagName("div");
                
                var t = "";
                var data = [];
                var color = [];
                var font = []; 
                
                var site_name = url10.replace(/.*\/{2}/g, "").replace(/\/.*/g, "");   
                      
                for (i = 0; i < h.length; i++) {	
                    if (h[i].className == "") {
                        if (h[i].innerText) t = (h[i].innerText);
                    }
                }

                if (t) {
                    data.push(site_name);
                    color.push("h1_color");
                    font.push("t2_font");
                
                    info_text_arr = data;
                    info_text_color = color;
                    info_text_font = font;

                    utils.WriteINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "lyrics", data.join("*"));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "lyrics_c", color.join("*"));
                    utils.WriteINI( path + "\\" + clean(t_artist) + "_title_info.ini", clean_ini(clean(t_title)), "lyrics_f", font.join("*"));
                }
                
                doc.close();
            }
            if (t) {
                text = t; 
                save_txt_file(t, file);
            } else {
                text = get_text_nf(lang_arr[lang_idx]);
            }
            get_text_array();
        }
    }						
}

function get_artist_external_links(path, t_artist){		
    xmlhttp11 = new ActiveXObject("Microsoft.XMLHTTP");					
    url11 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(t_artist));
    xmlhttp11.open("GET", url11, true);					
    xmlhttp11.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp11.send(null);							
    xmlhttp11.onreadystatechange = function () {							
        if (xmlhttp11.readyState == 4) {							
            if (xmlhttp11.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp11.responsetext;
                var a = div.getElementsByTagName("a");	

                var tmp_data = [];
                var data = [];
                             
                for (i = 0; i < a.length; i++) {
                    if (a[i].className.indexOf("resource-external-link") >= 0){ 
                        tmp_data.push(a[i].innerText);
                        tmp_data.push(a[i].href);
                    }
                } 
                
                for (i = 0; i < tmp_data.length / 2; i++) {
                    data.push(tmp_data[i]);
                } 
                
                external_links = data;
                utils.WriteINI( path + "\\" + clean(t_artist) + "_artist_info.ini", clean_ini(clean(t_artist)), "external_links", data.join("*"));
                
                doc.close();							
            } 
        }
    }							
}

var scroll = 0, scroll_ = 0, scroll__ = 0, scroll___ = 0;
var scroll_timer;
var scroll_timer_on = false;

function scroll_check(){
    if (scroll >= 0){	
        scroll = 0;
    } else if (Math.abs(scroll) + text_visable_height >= text_height){
        scroll = (text_height - text_visable_height) * -1; 
    }

    !scroll_timer_on && text_scroll_timer();
}

function text_scroll_timer(){
    scroll_timer_on = true;
    scroll_timer && window.ClearInterval(scroll_timer);
    scroll_timer = window.SetInterval(function() {
        if (Math.abs(scroll - scroll_) > 0.1){	
            k = on_scrollbar_down ? 1.5 : (on_seekbar_down ? 2 : 3 + scroll_key_k);
            
            scroll___ += (scroll - scroll___) / k ;			
            scroll__ += (scroll___ - scroll__) / k;		
            scroll_ += (scroll__ - scroll_) / k;
        } else {
            window.ClearInterval(scroll_timer);
            scroll_ = scroll;
            scroll_timer_on = false;
            scroll_key_k = 0;
        }
        
        wheel_id = 0;

        text_idx = Math.round(Math.floor((pos_y - t_y) / text_row_height) + scroll * -1 / text_row_height);
        selected_item = selected_item_rows_tmp[text_idx];
        selected_item_rows = [];

        for (var j = 0; j < selected_item_rows_tmp.length; j++) {
            if (selected_item_rows_tmp[j]) {
            
                if (t_y + (j * text_row_height) - (scroll * -1) > 0){
                    window.RepaintRect(t_x, t_y + (j * text_row_height) - (scroll * -1), text_row_width, text_row_height);
                }
            
                if (selected_item_rows_tmp[j] == selected_item) {
                    selected_item_rows.push(j);
                } 
            } 
        }

        window.RepaintRect(t_x, t_y - text_row_height, ww - t_x, wh);
    }, 40);    
}

function help(){
    var button_type = 0x0;
    var icon_type = 0x20;

    switch (lang_arr[lang_idx]) {
    case "ru":
        var title = "Справка по сочетанию клавиш и настройкам";
        var txt = 
        '- выбор языка - двойной щелчок ЛКМ (или ЛКМ + Shift) на тексте или через меню (настройка - "Select of languages") ;' + '\n\n' + 
        '- размер шрифтов - Shift и КОЛЕСО на тексе или на заголовках текста (выбор шрифта и стиля - меню "Properties", выравнивание - "Text alignment")' + '\n\n' +     
        '- передвижение текста - при нажатой ЛКМ ;' + '\n\n' + 
        '- спрятать / восстановить текст - двойной щелчок СКМ ;' + '\n\n' + 
        '- прозрачность фона под текстом - Ctrl + КОЛЕСО на тексте ;' + '\n\n' + 
        '- смена изображения - КОЛЕСО на изображении ;' + '\n\n' + 
        '- установка интервала смены изображения - Shift и КОЛЕСО на изображении ;' + '\n\n' + 
        '- выбор: "Исполнитель", "Альбомы исполнителя", "Похожие исполнители", "Альбом" (активен, если есть информация), "Информация о треке" или "Текст (лирика)" - двойной щелчок ЛКМ на изображении или через меню ;' + '\n\n' + 
        '- включить / отключить пункты контекстного меню - "Menu setting" .' + '\n\n' +  
        '- дополнительные настройки - меню "Properties" .' 
        break
    default:
        var title = "Keyboard shortcut and settings help";
        var txt = 
        '- select language - double click LMB (or LMB + Shift) on the text or through the menu (the setting is "Select of languages");' + '\n\n' +
        '- font size - Shift and WHEEL on tex or text headings (font and style selection - "Properties" menu, alignment - "Text alignment")' + '\n\n' +
        '- move the text - while pressing the LMB;' + '\n\n' +
        '- hide / restore text - double-click MMB;' + '\n\n' +
        '- the background transparency under the text - Ctrl + WHEEL on the text;' + '\n\n' +
        '- change the image - the WHEEL on the image;' + '\n\n' +
        '- set the interval of the image change - Shift and the WHEEL on the image;' + '\n\n' +
        '- select Artist, Top Albuums, Similar Artist, Album info, Track Info or Lyrics - Double-click on the LMB in the image or through the menu ; ' + '\n\n' +
        '- enable / disable the context menu items - "Menu setting".' + '\n\n' +
        '- additional settings - menu "Properties" .'
        break
    }
    
    var btn = WshShell.Popup(txt, 0, title, button_type + icon_type);
}
			
function print(msg) {
    try {    
        fb.trace(msg);   
    } catch(e){console.log(msg);};         
}
					
function on_notify_data(name, info) {
    if (name == "panel") {
        if (info == "bio"){
            panel_on = true;
            meta_artist = "";
            on_metadb_changed();
        } else {
            panel_on = false;
        }
    }
}

function draw_popularity_rank(gr) {
    pr = "#18";
    
    pr_font = gdi.Font(font_name_t, font_size_t, 1);
        
    pr_w = gr.CalcTextWidth(pr, t2_font);
    pr_h = gr.CalcTextHeight(pr, t2_font);
    pr_d = Math.max(pr_w, pr_h);
        
    pr_x = txt_x + pr_d / 2;
    pr_y = txt_y - pr_d / 1;
        
    gr.SetSmoothingMode(2);

    gr.DrawEllipse(pr_x - 3, pr_y - 3, pr_d + 6, pr_d + 6, 4, t_color);
    gr.FillEllipse(pr_x - 3, pr_y - 3, pr_d + 6, pr_d + 6, RGB(255, 153, 0));
    gr.GdiDrawText(pr, t2_font, t_color, pr_x, pr_y + 1, pr_d, pr_d, DT_SINGLELINE | DT_CENTER | DT_VCENTER );
}

function write_history(n) {
    if (!fso.FileExists(history_file_path)) fso.CreateTextFile(history_file_path );	
    if (!n) return;
    var tmp_arr = [];
    
    if (fso.FileExists(history_file_path)){
        exist = false;
        tmp_arr = utils.ReadTextFile(history_file_path).split("\n");

        for (var i = 0; i < tmp_arr.length; i += 1) {
            if (trim(tmp_arr[i]) == trim(n)){
                exist = true;
                break;
            }
        }

        if (!exist){
            try {
                history_file = fso.OpenTextFile( history_file_path, 8 );
                history_file.WriteLine(n);
                history_file.Close(); 
            } catch(e) {};        
        }
    }
}

function get_history(){
    clear_txt_var();
    var tmp_arr = [];
    history_arr = [];

    if (fso.FileExists( history_file_path)){
        tmp_arr = utils.ReadTextFile(history_file_path).split("\r\n").sort();

        if (tmp_arr.length > 0){
            for (var i = 0; i < tmp_arr.length; i += 1) {
                if (!tmp_arr[i]) tmp_arr.splice(i, 1);
            }     
            
            for (var i = 0; i < tmp_arr.length; i += 1) {
                if (tmp_arr[i].substring(0, history_seach.length).toLowerCase() == history_seach.toLowerCase()){
                    history_arr.push(tmp_arr[i]);
                }
            }

            if (history_arr.length == 0) {
                history_arr = tmp_arr;
            }
        } else {
            history_arr = ["the list is empty"];
        }

        header_1 = history_seach;
        refresh_txt = true;
        get_text_array();
    }
}